How to transform screen position to global through a Camera2D?

Godot Version

v4.2

Question

I’m trying to use Camera2D and screen touch to move and zoom the viewport.

I tried to use Camera2D.global_transform * touch.position. However, it doesn’t take camera zoom into account.

In Unity, there is a Camera.ScreenToWorldPoint() method. How to achieve the same function in Godot?

In Unity, there is a Camera.ScreenToWorldPoint() method. How to achieve the same function in Godot?

It looks like there is a conceptional difference between Unity and Godot.

In Godot, Camara2D is a tool used to set the view of the viewports default canvas layer. In order to access the transform between the canvas layer and the screen, you need to get it via the viewport.

In order to convert screen coordinates to world coordinates (my guess would be, that you mean canvas layer coordinates, but you might also mean viewport coordinates; the word “global” is very ambiguous) please try:

canvas_layer_pos = (get_viewport().get_screen_transform() * get_viewport().get_canvas_transform()).affine_inverse() * screen_pos

I would like to point you to Viewport and canvas transforms — Godot Engine (latest) documentation in English which has some examples of the transform functions.

You should also be aware that the position of input events depends on the context, from which they are accessed.

Thanks for your explanation. That helped me find the right direction.

I found another useful document on this: https://docs.godotengine.org/en/latest/contributing/development/core_and_modules/2d_coordinate_systems.html#doc-2d-coordinate-systems

In my case, the touch input event position is got through _input(), which is in viewport coordinates. To transform it to the canvas behind Camera2D, only the viewport’s canvas_transform is needed.

canvas_pos = get_viewport().get_canvas_transform().affine_inverse() * touch_event.position
3 Likes

Thank you! :raised_hands: