Sprite animation dependant on object direction

I am making a 2d sprite in a 3d world and have been looking for/thinking of a way to get my 2d sprite (which has a set of images for each of 4 directions) to change which set of images it is using dependent on its current direction that it is either facing/moving (based on the y axis). This is for a click to move by the way, kind of like Ragnarok online.

my thoughts were to find the direction the object is facing and get it to change the animation with if statements.

i.e.

  1. if (playerMove == true){
  2. if (Lookat.y == >0 && <90) {
    
  3.     playFront() ;
    
  4. }
    
  5. if (Lookat.y == >179 && <270) {
    
  6.     playLeft() ;
    
  7. }
    
  8. if (Lookat.y == >179 && <270) {
    
  9.     playBack() ;
    
  10. }
  11. if (Lookat.y == >269 && <1) {
  12.    playright() ;
    
  13. }
  14. }

at the current point in time i’m not even sure if i’m using the right approach for this sort of problem.

any input is greatly appreciated.

I know the thread is old, but I stumbled on it while searching for a solution myself and eventually pieced one together. I hope it helps someone.

Vector2 me = transform.position \\The object that I want to turn
Vector2 target = *player*.transform.position \	he target I want to turn to (in my case the player)
CalculateAngleForAnim(me, target);
    
private void CalculateAngleForAnim(Vector2 me, Vector2 target)
        {
            float angleBetween = AngleBetweenVector2(me, target);
    
            if (angleBetween >= 45 && angleBetween < 135)
            {
                //up
            }
            else if (angleBetween >= 135 || angleBetween < -135)
            {
                //left
            }
            else if (angleBetween >= -135 && angleBetween < -45)
            {
                //down
            }
            else if (angleBetween >= -45 && angleBetween < 45)
            {
                //right
            }
        }

 private float  AngleBetweenVector2(Vector2 vec1, Vector2 vec2)
        {
            Vector2 diference = vec2 - vec1;
            float sign = (vec2.y < vec1.y) ? -1.0f : 1.0f;
            return Vector2.Angle(Vector2.right, diference) * sign;
        }

This answer was invaluable to get it working.

Cheers @fermmmm for the comment.

My suggestion would be to attach an animator object and pass in your facing_x and facing_y variables as floats (or ints) to the animator.

You can then create a blend tree in your animator that says ‘if facing_x = 0 and facing_y = 1’ load the facing_right sprite.

Here’s a great forum thread detailing this approach (look at keely’s post):
http://forum.unity3d.com/threads/animator-state-machine-for-top-down-2d-games-with-non-rotational-sprite-animation.212172/

I also have a code sample in my game that you can see here: