Keeping UI elements on screen and in variable positions?

Godot Version

Godot 4.6

Question

I'm trying to make the kind of info window or menu that shows up when the player clicks on a character on screen. The window should appear near the clicked location, while staying entirely on screen if the character is near the screen edge. I could of course clamp the target position (where the window appears) using the screen size and menu size, I just wonder if there's any built-in setting that can achieve the effect. Thanks.

Is this for 2D or 3D?

For 2D you can simply make a small function that can translate a position in 2D space into a viewport position, something like this:

func worldToViewport(target: Node2D) -> Vector2:
	var targetCavnasPos: Vector2 = target.get_screen_transform().origin.clamp(Vector2.ZERO, target.get_viewport_rect().size);
	return targetCavnasPos;

If it’s 3D, it’s even easier, since you can use a built in function called unproject_position on the camera 3D, something like so:

func worldToViewport3d(target: Node3D) -> Vector2:
	var camera: Camera3D = target.get_viewport().get_camera_3d();
	return camera.unproject_position(target.global_transform.origin)

I’m doing it in 2D for now. Sounds like it’s just simple enough to not need dedicated native support. Thanks for your code!

1 Like