How to make a moving character look at the mouse?

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

The question seems obvious and there is a sample for it, but I can’t get it work properly in my game.
I have a camera as child of my character, so it moves following him.
It works… but when I resize the game window, the character doesn’t really looks at the right place, as if the center was offset on the left Oo

Here is the code I use in my character scene:

var mouse_pos = get_global_mouse_pos()
var sprite = get_node("sprite") # The sprite is centered already
sprite.look_at(mouse_pos)

And a sample: http://zylannprods.fr/dl/godot/LookAt.zip

Try playing the scene, then resize the window like the screenshots… the sprite doesn’t looks right. Is there something I did wrong?

EDIT: screenshots of the problem I’m experiencing. The red cross is the virtual point where the center seems to be offset.

:bust_in_silhouette: Reply From: PixelWizzard

Instead of just using get_global_mouse_pos(), try using this:

var mousePos = get_node("yourCamera").get_global_mouse_pos()
get_node("sprite").set_rot(get_node("sprite").get_pos().angle_to_point(mousePos))

I tried, but it doesn’t solves the problem. When I resize the window, the offset is still there.

Zylann | 2016-03-16 20:59

After trying out your project, I found the simplest solution to be the following:
in your project settings, under the display-tab, set the stretch_aspect - value to ignore
This means, that the stretch ratio is not kept the same anymore after resizing, whick kind of makes sense anyway, because you normaly don’t scale your window to the same ratio as before. The downside of this is that your scene can appear weirdly streched after resizing.

PixelWizzard | 2016-03-16 21:37

This works but as you said, I don’t want my game to be stretched. I could compute a counter-offset as a workaround, but I believe get_global_mouse_pos() doesn’t works as expected in this particular case.

Zylann | 2016-03-16 22:43

You could disable the stretch_mode and make use of camera_zoom to get the screen sizing.

vinod | 2016-03-17 17:49