How to determine direction when make player move_and_slide()

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


I’ve got a player which moves by mouse click. What I need to do is to determine direction in such a way that I could apply each of 8 animations.

I found tutorials concerning arrows movement, but couldn’t find anything about mouse click movement.

Every direction in this picture implies specific animation. How can I determine these directions?

:bust_in_silhouette: Reply From: TheFamousRat

Hello DeadZombie,

You might want to use the return value of “move_and_slide”. From the documentation : “Returns the movement that remained when the body stopped.”. As such, this method returns a Vector2 that is exactly that, the movement that remained. If you want the angle, you will have to use the “angle_to” method.

I haven’t tested what I’m writing, but to get this direction (which needs the angle), I’d do that :

var resultingMovement : Vector2 = move_and_slide(...)
var movAngle : float = resultingMovement.angle_to(Vector2(0,1))

The variable “movAngle” will be in radians and work as such : its value will be around 0 is the resulting movement goes upward, close to PI/2 if the body is going left, -PI/2 if it is going right etc. From that you can just put 8 conditions (for 8 directions) and check if the angle is within a certain interval.