Translate global position into screen position taking into account camera zoom

Godot Version

4.3

Question

I have a big 2D map. I need to move the player’s cursor to a certain place on this map. And I know exactly that this place is currently visible on the screen.

I’m going to translate the position of this place on the map to a position on the screen and then use Viewport.WarpMouse(localPos) to move the cursor there.

I use the formula: placePosition - Camera2D.GlobalPosition + GetViewportRect().Size / 2; and it works fine when Camera2D.Zoom == 1. But if the zoom is different - it doesn’t work.

I can’t figure out how to take the camera zoom into account.

In other topic i saw this was helpful 2D coordinate systems and 2D transforms — Godot Engine (latest) documentation in English
maybe you want draw some debug lines too?

1 Like

Solution is to multiply found offset by zoom:
(placePosition - _camera.GlobalPosition) * _camera.Zoom + GetViewportRect().Size / 2f;

1 Like

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