making the 2d sprite changing depending on mouse position

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

So i’m working on a 2d top-down arpg game and i want to know how i can make the sprite change depending on the location of the mouse, for example if the mouse is on the top part of the screen i want the sprite to face that way and if the mouse is creating a circle around the player i want the player sprite to look like as if its spinning. so does anyone know how i can code that into my game?

:bust_in_silhouette: Reply From: gba2511

You can get mouse position with get_viewport().get_mouse_position() and change sprite orientation with sprite.rotation = new_angle. So you need to attach following script to the sprite:

func _physics_process(delta):
	var mouse_position = get_viewport().get_mouse_position()
	var direction = (mouse_position - self.position).normalized()
	var new_angle =  PI + atan2(direction.y, direction.x) 
	self.rotation  = new_angle

There is a specific function for that: look_at(Vector2)

 func _physics_process(delta):

If your sprite points to the wrong side add this code at the end and change to the desired angle:

$Sprite.rotation -= PI


$Sprite.rotation_degrees -= -90

estebanmolca | 2020-05-28 05:38

Thank you very much. That did the trick !

iustinn | 2020-08-19 15:31

It also works if you just do this:

 func _physics_process(delta):

Sakuba | 2021-11-20 00:53