Get mouse position in world?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By mateusak
:warning: Old Version Published before Godot 3 was released.

You can get mouse position from the viewport, but how can you convert it to world position? Do I need to do it manually?

:bust_in_silhouette: Reply From: avencherus

If you want the mouse coordinates relative to your canvas, each Node2D inherits from a CanvasItem and gives a method called get_global_mouse_pos().

This is correct and works for me, but the correct name of the function is now get_global_mouse_position()

maxdifraia | 2020-08-16 15:48

get_global_mouse_position()

pc9098 | 2022-09-03 21:59

:bust_in_silhouette: Reply From: ascripter

I found get_global_mouse_position() to be insufficient in certain cases, i.e. when you wanna make an object (Light, Sprite) follow the cursor AND ProjectSettings.display/window/stretch/aspect is set to expand AND the window is resized. The object will then be misaligned.

So if you have a Light or Sprite or other Node2D that has an offset property, you can compensate for this effect like this:

position = get_global_mouse_position()
offset = get_local_mouse_position()

I assume the reason is that a global transformation is implicitly applied that results in a change of the local position (you can check by debugging get_global_transform() and realize that get_global_transform().xform_inv(get_global_mouse_position()) == get_local_mouse_position())