1. Unity人物移动+自动寻路
using UnityEngine;
using System.Collections;
public class PlayerCtrl : MonoBehaviour
{
public float MoveSpeed, RoteSpeed;
private Ray ray;
private RaycastHit hit;
private UnityEngine.AI.NavMeshAgent _NMA;
private Animator _Anima;
private bool IsRun;//是否奔跑
private float ver, hor;
private int IsRunBoolID;//IsRun的Hash
void Awake ()
{
//得到自身组件
_Anima = GetComponent<Animator>();
_NMA = GetComponent<UnityEngine.AI.NavMeshAgent>();
//IsRunBoolID = Animator.StringToHash("IsRun"); //Hash-1
}//end_Start
void Update ()
{
//动画
//_Anima.SetBool(IsRunBoolID, IsRun); //Hash-2
_Anima.SetBool("IsRun", IsRun);
//鼠标点击移动
if (Input.GetMouseButtonDown(0))
{
//射线投射信息
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
//导航到鼠标点击出
_NMA.destination = hit.point;
//重新开启导航
_NMA.Resume();
}
}
//WASD控制移动
hor = Input.GetAxis("Horizontal");
ver = Input.GetAxis("Vertical");
//hor或ver不为0,表示有从wasd的输入,所以要终止导航,自己操作
if (ver!=0||hor!=0)
{
//关闭导航
_NMA.Stop();
IsRun = true;
//移动和旋转
transform.Translate(0, 0, ver * MoveSpeed * Time.deltaTime);
transform.Rotate(0, hor * RoteSpeed * Time.deltaTime, 0);
}
else
{
//如果wasd输入为0,才可能会自动导航
//导航的速度为0的时候,不奔跑;不为0,奔跑
if (_NMA.desiredVelocity!=Vector3.zero)
{
IsRun = true;
}
else
{
IsRun = false;
}
}
}//end_Update
}
2. 通过角色控制器控制移动