How to turn mouse coordinates in world coordinates?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By IndigoGames

So, there is, in unity, the function ScreenToWorldPoint() that transforms a point from screen space into world space.
Is there a similar function in godot?

:bust_in_silhouette: Reply From: denxi

get_local_mouse_position() will return the mouse’s co-ordinates relative to the node that you’re calling it from, while get_global_mouse_position() will return the mouse’s position relative to the current canvas layer.

1 Like
:bust_in_silhouette: Reply From: johnygames

Is this what you are looking for?

get_global_mouse_position()
:bust_in_silhouette: Reply From: estebanmolca

This is the closest thing I know in godot.
Look at the camera methods in the documentation, such as:

Vector3 project_position (screen_point: Vector2, z_depth: float) const

Returns the 3D point in worldspace that maps to the given 2D
coordinate in the Viewport rectangle on a plane that is the given
z_depth distance into the scene away from the camera.

Or inverse:

Vector2 unproject_position (world_point: Vector3) const

Returns the 2D coordinate in the Viewport rectangle that maps to the
given 3D point in worldspace.

There is also something in the manual using Raycasting:

:bust_in_silhouette: Reply From: zowie

Pretty late to reply here, but if you need to convert from view space to world space in 2D, you can use Node.get_canvas_transform().affine_inverse() to get the view-to-world-space transformation matrix.

To convert a view space position to a 2D world space position, you can use the following code:

var view_to_world = YOUR_NODE.get_canvas_transform().affine_inverse()
var world_position = view_to_world * view_position

Similarly, converting from 2D world space to view space:

var world_to_view = YOUR_NODE.get_canvas_transform()
var view_position = world_to_view * world_position

Made an account, just to thank you!

SairamTheDeveloper | 2023-06-14 17:00

3 Likes

If you need to convert from viewport pixels to 3D world space, you can simply use the one-liner Camera3D.project_position, see Camera3D — Godot Engine (latest) documentation in English

The above saves you the bloat of raycasts and raycast queries, why would you bother with physics for this

If you mean, getting the object’s surface position where mouse is pointing, then I created a tutorial just for this. It uses ray-casting to do this under the hood.
i am late, but it will help people coming here in future.