我正在使用 c# 在 Unity 中创建 3D FPS 游戏。我有一个使用 NavMeshAgent 来巡逻一个区域的敌人 AI。我有一种方法可以在地图上选择一个随机位置,然后告诉敌人去那个点,一旦到达那个点,它应该在地图上选择另一个随机点,但是它只在某些时候有效. 有时它会在离点很近的地方停下,但不会停在点上,即使没有任何东西告诉它停下来,它也不会选择新的点。有谁知道这个问题的解决方案?
这是我的脚本:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using Random = UnityEngine.Random;
public class EnemyController : MonoBehaviour
{
public NavMeshAgent agent;
public LayerMask groundMask;
//Patrolling Area
public Vector3 walkPoint;
private bool walkPointSet;
public float walkPointRange;
// Start is called before the first frame update
void Start()
{
agent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update()
{
Patrol();
}
void Patrol()
{
if (!walkPointSet)
{
SearchWalkPoint();
}
Vector3 distanceToWalkPoint = transform.position - walkPoint;
//when walk point is reached
if (distanceToWalkPoint.magnitude < 1f)
{
walkPointSet = false;
}
}
void SearchWalkPoint()
{
//calculate random point in range
float randomZ = Random.Range(-walkPointRange, walkPointRange);
float randomX = Random.Range(-walkPointRange, walkPointRange);
walkPoint = new Vector3(transform.position.x + randomX, transform.position.y, transform.position.z + randomZ);
//checks if random walk point is inside of the map
if (Physics.Raycast(walkPoint, -transform.up, 3f, groundMask))
{
walkPointSet = true;
}
agent.SetDestination(walkPoint);
}
解决方案:我将变量 randomX 和 randomZ 添加到对象当前的 x 和 z 位置,这会创建某种偏移,从而影响某些随机值不被达到。解决方案只是将 randomX 和 randomZ 插入它们各自的点,而不是将数字添加到当前位置。更新后的代码如下:
walkPoint = new Vector3(randomX, transform.position.y, randomZ);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句