写代码之前,要先将地面设置静态,然后添加Navigation,进行烘焙场景,然后在玩家身上挂上
NavMeshAgent,就可以用代码控制玩家了


Animator an;
NavMeshAgent age;
public Transform cube;
// Start is called before the first frame update
void Start()
{
an = GetComponent<Animator>();
age = GetComponent<NavMeshAgent>();
//age.destination = cube.position;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
age.SetDestination(hit.point);
transform.LookAt(hit.point);
}
}
if (age.remainingDistance<=1f)
{
an.SetFloat("run",0);
}
else
{
an.SetFloat("run",1);
}
}
本文介绍了一种在Unity中实现玩家控制的方法,通过设置地面为静态并应用Navigation,进行场景烘焙,然后在主角身上挂载NavMeshAgent组件。在代码层面,当点击鼠标时,通过Raycast确定目标点,设置NavMeshAgent的目标位置,并更新角色的动画状态以反映移动情况。
3367

被折叠的 条评论
为什么被折叠?



