Centering a PanelContainer when repositioning via code

Godot Version

4.5.1

Question

Let’s say you have this tree structure.

  • PanelContainer
    • Label

The label is centered. You want to set the screen space position of the container to a specific point in the world (using camera.unproject_position) every frame. The PanelContainer should be centered on that point. The label can change every frame, as it contains a number counting up rapidly.

Here’s my latest attempt, which does not work.

func _process(_delta: float) -> void:
	if not node_to_follow or not camera:
		return

	var world_position: Vector3 = node_to_follow.global_position + Vector3(0, 1.25, 0)
	var screen_position: Vector2 = camera.unproject_position(world_position)
	global_position = screen_position - size * 0.5
	pivot_offset = size / 2

label_center
You can see that it’s centered when scale is one, and then offset when scale is doubled.

Is there an easy solution to this problem?

I realized the solution seconds after posting this.
I forgot to account for the scale when adjusting for the size. So this works:

global_position = screen_position - size * 0.5 * scale
1 Like