+1 vote

I am having an issue with the player not facing the mouse cursor when the camera is a child of the player (to move with it). This is the code I use to look towards cursor. It runs on the player, which is a RigidBody2D.

# Makes player face towards cursor
var mpos = get_viewport().get_mouse_pos()

It is as if the player center is stuck on a certain position in the world; so that when I move the player away from where it was; the center of the player (where facing direction is being calculated) is stuck in space; regardless of camera movement. :S

The mouse coordinates on the screen does not move with the camera.

So far I have discovered that the on-screen mouse coordinates do not change when moving the camera. This mean I will need to add x and y from the player position. Are there any in-engine function to handle this for me? Else I will just have to do the math myself

Any tips or advice how I can get the camera and on-screen mouse coordinates to follow the camera?

Solution found:
At first I managed to solve it by using this line to get mouse coordinates;

var mpos = get_viewport().get_mouse_pos() + get_pos() - OS.get_window_size() / 2

... and then someone answered this question and it turned into

var mpos = get_global_mouse_pos()

I like the second one better :)

in Engine by (495 points)
edited by

2 Answers

+3 votes
Best answer


by (50 points)
selected by
Thank you!
Saves me from having to type in a long line of code :)
+2 votes

Have you tried using self.get_global_mouse_pos() instead? Maybe the viewport only gives you the mouse position in viewport coordinates.

by (372 points)
Thank you! Much better than the solution I came up with xP
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 webmaster@godotengine.org with your username.