2D 8-directional enemy AI sprite animation with Blend Tree not using correct animations

Hi all,

I have a simple 2D top-down shooting game. I created a BlendTree and Animator Controller for my Player to animate in 8 directions, and that works great. The issue I’m having is getting the enemy AI to do the same thing. I’ve applied the Animator Controller I’m using on my Player to my Enemy AI.

This is the technique I used to add the Blend Tree: Unity Top Down Character Movement and Animation with Blend Tree - Tutorial - YouTube

Here’s my Enemy script Update function (Just spawns and moves toward the Player):

  void Update()
  {
      transform.position = Vector2.MoveTowards(transform.position, playerPos.position, speed * Time.deltaTime);
      
      anim.SetFloat("VerticalSpeed", transform.position.y);
      anim.SetFloat("HorizontalSpeed", transform.position.x);
      anim.SetFloat("Magnitude", transform.position.magnitude);
  }

My Enemy script’s Start func:

 void Start()
  {
      player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>();
      // Gets the Player's position
      playerPos = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
      rb = GetComponent<Rigidbody2D>();

      anim = GetComponent<Animator>();
  }

So it’s obviously what I’m sending to the Animator in terms of the speed and magnitude that is causing the issue. Obviously my Player character can be anywhere on the screen so I’m guessing because the Enemy is following the Player, the input values for the Animator mean they won’t be congruent with the required values of the correct animation that needs to play (if that makes sense)?

As I’m using the exact same Blend Tree technique with the Player, when I go left it will use the left walking animation, when I go right the right animation etc. Where as when the Enemy goes left he’ll tend to use a somewhat opposite animation (but it’s always kind of random).

Once the enemy gets close enough to the Player, he will sometimes play the correct animation

Not sure if there’s anything else I need to add but if you need more code for something then let me know.

Thanks!

https://answers.unity.com/questions/1752521/how-to-intigrate-enemy-animation-blend-tree-to-mov.html?childToView=1920815#answer-1920815

i did it using 4 directional animation but i think its the same
its not a very good way to do but i think it worked!