How can I make a 4 direction animation for an enemy?
I'm trying to animate a 2d enemy in 4 directions, I tried making a blend tree but I couldn't find or figure out any compatible code with my AI code. Can anyone help?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy2AI : MonoBehaviour
{
public float speed;
public float lineOfSite;
public float shootingRange;
public GameObject bulletPrefab;
public GameObject bulletParent;
public float fireRate = 1f;
private float nextFireTime;
private Transform player;
// Start is called before the first frame update
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
}
// Update is called once per frame
void Update()
{
float distanceFromPlayer = Vector2.Distance(player.position, transform.position);
if (distanceFromPlayer < lineOfSite && distanceFromPlayer > shootingRange){
transform.position = Vector2.MoveTowards(this.transform.position,player.position,speed * Time.deltaTime);
}
else if (distanceFromPlayer <= shootingRange && nextFireTime < Time.time){
Instantiate(bulletPrefab, bulletParent.transform.position, Quaternion.identity);
nextFireTime = Time.time + fireRate;
}
}
private void OnDrawGizmosSelected() {
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(transform.position, lineOfSite);
Gizmos.DrawWireSphere(transform.position, shootingRange);
}
}
Answer by TheIrishKraken · May 15 at 10:57 PM
A blend tree is definitely the way to go, you set up one for your Idle animations (if you have some) and one for movement animations. You need to store your enemies movements on the X & Y then change its animations depending on the direction its facing.
Here's a blend tree I use for my character in one of my 2D games.
My player has a movement.x and a movement.y in its script. In my update I check to see if movement.x or movement.y is greater then or less then 0 and play the corresponding animations.
Create a Vector2 movement in your script & store your enemies transform.position in it. Inside Update check if your enemy is moving on the X or Y axis and change the animation in the blend tree depending on his direction.
if (this.transform.position.x > 0) { animator.SetFloat("Vertical", movement.x); }
I hope this helps some bit or at least steers you in the right direction.
Your answer
Follow this Question
Related Questions
2D Enemy Ai 0 Answers
Animation with different behaviors for different directions. 1 Answer
How to immediately CHANGE SPEED from spotted position to another?) 1 Answer
AI stops following player. 1 Answer
Boss ai help EoW 0 Answers