unity对象在一定的范围内随机行走
时间: 2024-05-02 18:19:31 浏览: 152
unity鱼随机移动
可以使用Unity的NavMeshAgent组件来实现对象在范围内的随机行走。首先,需要在导航网格中创建区域,然后将NavMeshAgent组件添加到对象上。接下来,可以使用随机数生成器来计算对象的下一个目标点,并使用NavMeshAgent组件将对象移动到该点。代码示例:
```
[SerializeField] private NavMeshAgent agent;
[SerializeField] private float walkRadius = 10f;
private Vector3 targetPosition;
void Start()
{
targetPosition = RandomNavSphere(transform.position, walkRadius, -1);
}
void Update()
{
if (agent.remainingDistance < 0.5f)
{
targetPosition = RandomNavSphere(transform.position, walkRadius, -1);
agent.SetDestination(targetPosition);
}
}
private Vector3 RandomNavSphere(Vector3 origin, float dist, int layerMask)
{
Vector3 randDirection = Random.insideUnitSphere * dist;
randDirection += origin;
NavMesh.SamplePosition(randDirection, out NavMeshHit navHit, dist, layerMask);
return navHit.position;
}
```
当对象到达目标点时,通过重新生成随机目标点,并使用NavMeshAgent组件将对象移动到该点,来实现对象在范围内的随机行走。
阅读全文