AI walking problem
My AI is supposed to chase the player when they are in a certain distance. The problem is that the AI does start to walk to the player but then switches back to idle and just slides towards the player.
Below is a screenshot of the animator for the AI. The transitions from idle to walk and walk to idle contain the conditions isChasing (set to true and false respectively).
The rest of the animations work as expected, attacking the player when they are at a certain distance. Below shows the script attached to the AI:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class ZombieAttack : MonoBehaviour {
private NavMeshAgent navMeshAgent;
public Transform target;
private Animator myAnimator;
public bool chaseTarget = true;
public float stoppingDistance = 2.5f;
public float delayBetweenAttacks = 1.5f;
private float attackCooldown;
private float distanceFromTarget;
// Use this for initialization
void Start()
{
navMeshAgent = GetComponent<NavMeshAgent>();
myAnimator = GetComponent<Animator>();
navMeshAgent.stoppingDistance = stoppingDistance;
attackCooldown = Time.time;
}
// Update is called once per frame
void Update()
{
if (Vector3.Distance(target.position, this.transform.position) < 15)
{
Vector3 direction = target.position - this.transform.position;
direction.y = 0;
this.transform.rotation = Quaternion.Slerp(this.transform.rotation, Quaternion.LookRotation(direction), 0.1f);
ChaseTarget();
}
else
{
//Turn running off
myAnimator.SetBool("isChasing", false);
chaseTarget = false;
}
}
void ChaseTarget()
{
distanceFromTarget = Vector3.Distance(target.position, transform.position);
if (distanceFromTarget >= stoppingDistance)
{
chaseTarget = true;
}
else
{
chaseTarget = false;
Attack();
}
if (chaseTarget)
{
navMeshAgent.SetDestination(target.position);
myAnimator.SetBool("isChasing", true);
}
else
{
myAnimator.SetBool("isChasing", false);
}
}
void Attack()
{
if (Time.time > attackCooldown)
{
Debug.Log("Attack");
myAnimator.SetTrigger("Attack");
attackCooldown = Time.time + delayBetweenAttacks;
}
}
}
I'm not sure where I am going wrong, and why the AI starts to walk but then slides to the player.
Appreciate any suggestions.
unity-animator.png
(170.9 kB)
Comment