在游戏运行时新加入如(或删除)建筑类的游戏物体时
using UnityEngine.AI;
class xx{
//注意!!!NavMeshSurface需要额外下载NavMeshsComponets
NavMeshSurface nms;
nms = GetComponent<NavMeshSurface>();
nms.BuildNavMesh();
}
//如果新加入的游戏物体没有bulid迹象,可能是因为游戏物体的高度没达到AgentType step height!!!
使用NavMeshAgent寻路,但是自己控制移动。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class NavigetAgent : MonoBehaviour {
//public Transform target;
bool isColider;
RaycastHit hit;
NavMeshAgent agent;
private void Start()
{
agent = GetComponent<NavMeshAgent>();
agent.updatePosition = false;
agent.updateRotation = false;//禁止agent控制角色
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
isColider = Physics.Raycast(ray, out hit);
}
if (isColider)
{
agent.nextPosition = transform.position;//将agent限制在角色内。我们只需要NavMeshAgent.desiredVlocity参数来取得前进方向即可
agent.destination=hit.point;
isColider = false;
}
if (agent.remainingDistance > 0.1f)
{
move();
}
}
void move()
{
agent.nextPosition = transform.position;
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(agent.desiredVelocity), 20 * Time.deltaTime);//NavMeshAgent.desiredVlocity 期望的速度?我觉得就是agent的前进方向!!!
transform.Translate(Vector3.forward * 4 * Time.deltaTime);//使用Translate时最好使用Vector3方向参数
}
}