Video 202: Lets Add A Zombie
Im currently having issues with the zombie sliding after completing the death animation. I’ve gone through the video again and also tried a solution posted on the Udemy Q&A. The zombie doesn’t chase the player when dead (which is good), but it just sort of slides back and fourth.
The enemyAI and navMeshAgent is disabled upon death.
using UnityEngine;
using UnityEngine.AI;
public class EnemyAI : MonoBehaviour
{
[SerializeField] Transform target;
[SerializeField] float chaseRange = 5f;
[SerializeField] float turnSpeed = 5f;
NavMeshAgent navMeshAgent;
float distanceToTarget = Mathf.Infinity;
bool isProvoked = false;
EnemyHealth health;
// Start is called before the first frame update
void Start()
{
navMeshAgent = GetComponent<NavMeshAgent>();
health = GetComponent<EnemyHealth>();
}
// Update is called once per frame
void Update()
{
if (health.IsDead())
{
this.enabled = false;
navMeshAgent.enabled = false;
}
else
{
distanceToTarget = Vector3.Distance(target.position, transform.position); //calcs the distance between enemy & target
if (isProvoked)
{
EngageTarget();
}
else if (distanceToTarget <= chaseRange)
{
isProvoked = true;
}
}
}
public void OnDamageTaken()
{
isProvoked = true;
}
private void EngageTarget()
{
Debug.Log(name + " engaging target " + target.name);
FaceTarget();
if (distanceToTarget >= navMeshAgent.stoppingDistance)
{
GetComponent<Animator>().SetBool("attack", false);
GetComponent<Animator>().SetTrigger("move");
ChaseTarget();
}
if (distanceToTarget <= navMeshAgent.stoppingDistance)
{
GetComponent<Animator>().SetBool("attack", true);
AttackTarget();
}
}
private void ChaseTarget()
{
navMeshAgent.SetDestination(target.position);
}
private void AttackTarget()
{
Debug.Log(name + " has seeked and is destroying " + target.name);
}
private void FaceTarget()
{
Vector3 direction = (target.position - transform.position).normalized;
Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * turnSpeed);
}
private void OnDrawGizmosSelected()
{
// Display the chase range when selected
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, chaseRange);
}
}