How can i make object follow mouse pos?

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

I want to make eyes that stay in sockets and Follow the mouse pos …
As if the character is looking at the mouse… (not angle but pos)
I have no idea how to get this done… plz help :frowning:

:bust_in_silhouette: Reply From: KoBeWi

First, you need a sprite for eye that will be able to visibly rotate (so e.g. if you set rotation to specific value, the eye will look at that direction).

Then it’s simple vector math:

#eye variable should be set to your eye sprite node
eye.rotation = (get_viewport().get_mouse_position() - eye.position).angle()

If you move your camera, this may not always work properly, so instead it could look like this:

#camera variable should be set to your current camera
var mouse_position = get_viewport().get_mouse_position() + camera.global_position
eye.rotation = (mouse_position - eye.global_position).angle()

I dont want the rotation though, i want the eyeball to move out of centre to the edges, like, 50pixels lets say and go up, if mouse is above, go left if mouse is to the left… : 0

Serenade | 2018-03-08 10:58

Well, the process is the same. Either make the eye a child of node that will rotate, and if the eye is off center of the parent, it will move along edges. Or use normalized rotation vector to set the position. Something like:

var direction = (get_viewport().get_mouse_position() - eye.position).normalized()
position = direction * distance

where distance is how far you want the eye to be from center.

KoBeWi | 2018-03-08 13:32

Thanks it works like a charm! <3

Serenade | 2018-03-08 14:38