- Home /
Question by
Mad_Tiger_2409 · Aug 12, 2016 at 12:03 PM ·
rotationanimatornavmeshagent
Animation and Nav Mesh Agent - rotation problem
Hi
I'm trying to create a AI enemy by using Nav Mesh Agent and animation controller. When I setup basic AI and Nav Mesh Agent enemy follows very well. But I don't know how to properly add animation. I have a Idle and walk animation. Idle works good. The problem is that when I add a walk animation enemy can't turn.
This is a C# code for AI:
public class Enemy_Pursuit : MonoBehaviour
{
public LayerMask detectionLayer;
private Animator anim;
private Transform myTransform;
private NavMeshAgent myNavMeshAgent;
private Collider[] hitColliders;
private float checkRate;
private float nextCheck;
private float detectionRadius = 5;
// Use this for initialization
void Start()
{
SetInitialReferences();
}
// Update is called once per frame
void Update()
{
CheckIfPlayerInRange();
}
void SetInitialReferences()
{
myTransform = transform;
anim = GetComponent<Animator>();
myNavMeshAgent = GetComponent<NavMeshAgent>();
checkRate = 0.7f;
}
void CheckIfPlayerInRange()
{
if((Time.time > nextCheck) && (myNavMeshAgent.enabled == true))
{
nextCheck = Time.time + checkRate;
hitColliders = Physics.OverlapSphere(myTransform.position, detectionRadius, detectionLayer);
if(hitColliders.Length > 0)
{
myNavMeshAgent.SetDestination(hitColliders[0].transform.position);
}
}
}
}
Comment
Best Answer
Answer by Mad_Tiger_2409 · Aug 12, 2016 at 02:55 PM
Ok, so I find a solution for my problem. I changed code from this topic: http://answers.unity3d.com/questions/540120/how-do-you-update-navmesh-rotation-after-stopping.html
Now it looks like this:
public class Enemy_Pursuitv2 : MonoBehaviour
{
private NavMeshAgent agent;
public float rotationSpeed = 10f;
Transform target;
void Start()
{
agent = GetComponent<NavMeshAgent>();
GameObject player = GameObject.Find("Player");
target = player.transform;
}
void Update()
{
// Code here that decides what target is
MoveTowards(target);
RotateTowards(target);
}
private void MoveTowards(Transform target)
{
agent.SetDestination(target.position);
}
private void RotateTowards(Transform target)
{
Vector3 direction = (target.position - transform.position).normalized;
Quaternion lookRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * rotationSpeed);
}
}
Then I added walk animation to animation controller and it works :)
Your answer
![](https://koobas.hobune.stream/wayback/20220612090639im_/https://answers.unity.com/themes/thub/images/avi.jpg)