在做泰斗破坏神的时候 有个自动导航到NPC的功能!
代码如下:没有BUG!但是为什么导航的时候会自动播放人物的run动画?
public class PlayerAutoMove : MonoBehaviour {
private NavMeshAgent navAgent;
public float minDistance = 1.0f;//设置寻路 到达终点的最小距离
public Transform targetTrans;
// Use this for initialization
void Start () {
navAgent = GetComponent<NavMeshAgent>();
}
public void SetDestination(Vector3 target) {
navAgent.enabled = true;
navAgent.SetDestination(target);
// Debug.Log("target:"+target);
}
// Update is called once per frame
void Update () {
if (navAgent.enabled) {
//当 每次 enabled navmesh agent的时候 可能来不及计算remainDistance 可能会为0
if (minDistance > navAgent.remainingDistance&&navAgent.remainingDistance>0.0f)
{
// Debug.Log("remianDistance:"+navAgent.remainingDistance+" minDistance:"+minDistance);
navAgent.Stop();
navAgent.enabled = false;
TaskManager.Instance.OnArriveDestination();
}
}
if (Input.GetMouseButtonDown(0)&&!EventSystem.current.IsPointerOverGameObject()) {
//SetDestination(targetTrans.position);
}
}
}
下面是我控制人物移动的代码!
public class PlayerMove : MonoBehaviour {
// Use this for initialization
public float velocity = 5.0f;
private Rigidbody playerRigid;
private Animator playerAnim;
void Start () {
playerAnim = GetComponent<Animator>();
playerRigid = GetComponent<Rigidbody>();
playerAnim.SetBool("PlayerRun",false);
}
// Update is called once per frame
void Update () {
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
float ySpeed=playerRigid.velocity.y;
// float playerY = transform.position.y;
if (Mathf.Abs(h) > 0.05f || Mathf.Abs(v) > 0.05f)
{
//要用 -1-1表示旋转的方向要用 Quaternion.LookRotation(new Vector3(h,0.0f,v));
//LookAt是朝向某个点 不是把 它自己的Z 轴转到某个方向
// transform.rotation = Quaternion.LookRotation(new Vector3(h,0.0f,v));
// Debug.Log("target:"+new Vector3(h,0.0f,v).normalized);
//transform.LookAt(new Vector3(h,playerY,v).normalized);
transform.LookAt(transform.position+new Vector3(h,0.0f,v));
if (playerAnim.GetCurrentAnimatorStateInfo(1).IsName("New State")) {
playerRigid.velocity = new Vector3(h * velocity, 0.0f ,v * velocity);
// Debug.Log("NewState!!!!");
playerAnim.SetBool("PlayerRun", true);
}
}
else {
playerRigid.velocity = new Vector3(0.0f,ySpeed,0.0f);
playerAnim.SetBool("PlayerRun",false);
}
}
}
playerAnim.SetBool("PlayerRun", true);
这里控制的状态机进入跑步状态