My NPC will random move around if he doesn’t detect player, I need help with the animation between Idle and walking, because my NPC will stop for a moment before he keeps wandering. The bug might happen at update(), I believe that it’s too fast so the animations switching between Idle and walking are pretty fast such as a glitch.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Golem : MonoBehaviour {
private Transform m_player;
private NavMeshAgent m_Nav;
private bool m_IsDetected;
private bool m_Attacked;
private float m_NextCheck;
private float m_RateCheck;
public float m_WanderRange = 10f;
private Vector3 m_WanderTarget;
//private Vector3 m_PlayerPos;
[SerializeField]
private float speed;
[SerializeField]
private Animator m_anim;
void Awake(){
m_player = GameObject.FindGameObjectWithTag (“Player”).transform;
m_Nav = GetComponent ();
m_RateCheck = Random.Range (0.2f, 0.4f);
}
void Update () {
speed = m_Nav.speed;
checkDistanceToDetected ();
if (Time.time > m_NextCheck) { // this allow NPC stop a moment and wander again
m_NextCheck = Time.time + m_RateCheck;
chaseToPlayer ();
}
}
void checkDistanceToDetected(){
float distance = Vector3.Distance(transform.position, m_player.position);
Vector3 direction = m_player.position - this.transform.position; // direction for npc see player
float angle= Vector3.Angle(direction,this.transform.forward); // angle for npc see player
if (distance <= 20 && angle <110 ) { // 60 is the angle vision of NPC , <60 it means player stay inside NPC vision.
m_IsDetected = true;
if (distance <= 5) {
m_Attacked = true;
} else {
m_Attacked = false;
}
}
else
{
m_IsDetected = false;
m_anim.SetBool(“Run”,false);
}
}
bool randomWanderTarget(Vector3 centre , float range , out Vector3 result){ // centre is the start point , random wander function
NavMeshHit Navhit;
Vector3 randomPoint = centre + Random.insideUnitSphere * range;
if (NavMesh.SamplePosition (randomPoint, out Navhit, 1, NavMesh.AllAreas)) {
result = Navhit.position;
return true;
} else {
result = centre;
return false;
}
}
void chaseToPlayer(){ // chase player
if (m_IsDetected && m_player != null) {
m_anim.SetBool(“Run”,true);
m_Nav.speed = 8f;
m_Nav.SetDestination (m_player.position);
if (m_Attacked) {
m_anim.SetBool(“Run”,false);
m_anim.SetBool (“Attack”, true);
} else {
m_anim.SetBool (“Attack”, false);
}
} else if (!m_IsDetected) {
m_anim.SetBool(“Run”,false);
m_Nav.speed = 3.5f;
if (randomWanderTarget (transform.position, m_WanderRange, out m_WanderTarget)) {
m_Nav.SetDestination (m_WanderTarget);
}
}
}
// IEnumerator delay(){
//
// yield return new WaitForSeconds (5);
// if (m_IsDetected && m_player != null) {
// m_anim.SetBool (“Walking”, true);
// m_Nav.SetDestination (m_PlayerPos);
// } else if (!m_IsDetected) {
// if (randomWanderTarget (transform.position, m_WanderRange, out m_WanderTarget)) {
// m_anim.SetBool (“Walking”, true);
// m_Nav.SetDestination (m_WanderTarget);
// }
// }
// }
}