Hi!
I can’t figure out what I’m doing wrong. My enemy does not rotate at all. The enemy behaves exactly the way Ricks does, except it stays facing a constant direction. I’m unsure if it is something in my code because I replaced mine with Rick’s and the enemy still suffered with the same problem.
When playing the game, the rotation values remain at 0 regardless of where I place the player.
I’ve pasted my code below. Please may someone be kind enough to help me find out what I’ve done wrong? I’m really stumped this time lol
Thank you!
using System;
using System.Collections;
using System.Collections.Generic;
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;
void Start()
{
navMeshAgent = GetComponent<NavMeshAgent>();
}
void Update()
{
distanceToTarget = Vector3.Distance(target.position, transform.position);
if (isProvoked)
{
EngageTarget();
}
else if (distanceToTarget <= chaseRange)
{
isProvoked = true;
}
}
private void EngageTarget()
{
FaceTarget();
if (distanceToTarget >= navMeshAgent.stoppingDistance)
{
ChaseTarget();
}
if (distanceToTarget <= navMeshAgent.stoppingDistance)
{
AttackTarget();
}
}
private void ChaseTarget()
{
GetComponent<Animator>().SetBool("Attack", false);
GetComponent<Animator>().SetTrigger("Move");
navMeshAgent.SetDestination(target.position);
}
private void AttackTarget()
{
GetComponent<Animator>().SetBool("Attack", true);
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(transform.position, chaseRange);
}
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);
}
}