+11 votes

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

in Engine by (1,120 points)

2 Answers

+12 votes
Best answer

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().


by (5,276 points)
selected by

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


+3 votes

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())

by (20 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.