How do I know if my 2D character is moving left, right, top, down, or even 8 directions on compass

Hi.
I’m currently using AIPath (2D).

My character is moving properly under the control of A*. I do need to add animation. So I’ve currently got my character animating in idle.

I’ve added Up, Down, Left, Right Animations to my AnimatorController. I’m now working to update the state machine so that as AIPath moves my character I swap in the correct animation.

Is there already an attribute that I can look at on the AIPath that will give me a direction on a 2D compass, or at least 4 to 8 directions on a compass?

Any recommendation would be appreciated.


Follow up … what I might like is a vertical and horizontal indicator (each in the range -1 to 1). What is the best way to get this from the object that is being controlled by AIPath?

This approach can be seen in this brackeys video:

brackeys video

Simple answer was to use the AIPath velocity, maxSpeed, and speed fields to compute. This works.

private void UpdateAnimationDetail()
    {
        animationDetail.speed = aiPath.velocity.magnitude;
        animationDetail.horizontal = aiPath.velocity.x / aiPath.maxSpeed;
        animationDetail.vertical = aiPath.velocity.y / aiPath.maxSpeed;
    }
2 Likes