using UnityEngine;
using System.Collections;
public class EnemyAnimation : MonoBehaviour
{
public float speedDampTime = 0.3f;
public float anglarSpeedDampTime = 0.3f;
private NavMeshAgent navAgent;
private Animator anim;
void Awake()
{
navAgent = this.GetComponent<NavMeshAgent>();
anim = this.GetComponent<Animator>();
}
void Update()
{
if (navAgent.desiredVelocity == Vector3.zero)
{
anim.SetFloat("Speed", 0, speedDampTime, Time.deltaTime);
anim.SetFloat("AnglarSpeed", 0, anglarSpeedDampTime, Time.deltaTime);
print("test");
}
else
{
float angle = Vector3.Angle(transform.forward, navAgent.desiredVelocity);
float angleRad = 0f;
if (angle > 90)// 大于90度就进行旋转,小于90才走
{
anim.SetFloat("Speed", 0, speedDampTime, Time.deltaTime);
}
else
{
Vector3 progection = Vector3.Project(navAgent.desiredVelocity, transform.forward);
anim.SetFloat("Speed", progection.magnitude, speedDampTime, Time.deltaTime);
}
angleRad = angle * Mathf.Deg2Rad;
Vector3 corssRes = Vector3.Cross(transform.forward, navAgent.desiredVelocity);
if (corssRes.y < 0)
{
angleRad = -angleRad;
}
anim.SetFloat("AnglarSpeed", angleRad, anglarSpeedDampTime, Time.deltaTime);
}
}
}
如上代码,在untiy中也是没有报错的,机器人实际上就在第二点走不到第三个点,但是NavMeshAgent却正常,这时什么原因?
百度下,原来是新版本的问题,在update最后补上 navAgent.nextPosition = transform.position;这句代码,将NavMeshAgent和机器人位置同步就好了。