im trying to make an ai play an animation when he walks in a certain direction. for example when he walks left he plays the walk animation. and when he stops he stays facing left. right now i can only seem to get it to work when i give the input like the ai is a player. here is my script as of right now
public class EnemyMovement : MonoBehaviour {
public Transform player;
public float speed;
public float maxDistance;
public float minDistance;
public Vector2 lastMove;
public string startPoint;
public float attackTime;
public bool canMove;
private float moveX;
private float moveY;
private bool attacking;
private Animator anim;
private bool enemyMoving;
private Rigidbody2D myRigidbody;
private static bool enemyExists;
private float currentMoveSpeed;
private float attackTimeCounter;
private Vector2 moveInput;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
anim = GetComponent<Animator>();
myRigidbody = GetComponent<Rigidbody2D>();
canMove = true;
lastMove = new Vector2(0, -1f);
if (!enemyExists)
{
enemyExists = true;
DontDestroyOnLoad(transform.gameObject);
}
else
{
Destroy(gameObject);
}
}
void Update()
{
if (Time.timeScale == 0f)
{
return;
}
enemyMoving = false;
moveInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")).normalized;
if (moveInput != Vector2.zero)
{
if ((Vector2.Distance(transform.position, player.position) < maxDistance)
&& (Vector2.Distance(transform.position, player.position) > minDistance))
{
transform.position = Vector2.MoveTowards(transform.position, player.position, speed * Time.deltaTime);
}
enemyMoving = true;
lastMove = moveInput;
}
anim.SetFloat("MoveX", Input.GetAxis("Horizontal"));
anim.SetFloat("MoveY", Input.GetAxis("Vertical"));
anim.SetBool("EnemyMoving", enemyMoving);
anim.SetFloat("LastMoveX", lastMove.x);
anim.SetFloat("LastMoveY", lastMove.y);
}
}
`