- Home /
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: https://www.youtube.com/watch?v=32VXj5BB7wU
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!
Your answer
Follow this Question
Related Questions
Can you make a blend tree only play one animation at a time? 2 Answers
How I make my enemy face the player or flip towards player (top-down game)? 0 Answers
Unity2D Animation issues 1 Answer
2D Animation does not start 1 Answer
How to prevent holding down a key to infinitely loop an action? 1 Answer