How to tie a UI node to a 3d node

Godot 4.2.1

I’d like to have a Health Bar (TextureProgressBar) linked in position to the player in my game, so that when the player moves, the health bar moves with them.
Any ideas on how to accomplish this?

1 Like

You stablish a start position and an end position on the X axe. Then you just set the bar size to the difference of the player positions with the start position divided by the end position minus the start position and then multiply all that by the max bar size.

If you’d like a quick and dirty way of doing it, use a ViewportTexture on a quad.

image

This might be inefficient as all hell. I’m not actually sure. But it does the job.

You could also attach a script to the control in order to update the position based on the unprojected 3d position:

extends Control

@export var target: Node3D
@export var offset_3d: Vector3


func _process(_delta):
    var pos_3d := target.global_position + offset_3d
    var cam := get_viewport().get_camera_3d()
    var pos_2d := cam.unproject_position(pos_3d)
    global_position = pos_2d
    visible = not cam.is_position_behind(pos_3d)

Attach that to the control node. Then in the inspector select the 3d node as the target, and set an appropriate offset (for example Vector3(0, 1, 0) to show it one meter above the 3d object).

I used an empty Control of size 0 with the script attached, and then added the progress bar as a child. This way the progress bar can be easily centered using the default UI layout options.:

This is what the result looks like with the above node setup:

3 Likes

these examples might also help you

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.