我正在制作一个塔防游戏,其中NavMeshAgents通过从生成点到末端的路径行进。我的所有敌人(目前)都走相同的路,但是他们以不同的速度走。目前,我的塔楼始终以最靠近它们的敌人为目标。我希望我的塔楼瞄准需要沿着路径行进最短距离才能到达终点的敌人。
我尝试使用agent.remainingDistance,但是它一直返回Infinity(并且根据文档,这意味着代理不知道剩余距离)。
Tower.cs:
public Transform target;
// a lot of other stuff
void UpdateTarget()
{
GameObject[] enemies = GameObject.FindGameObjectsWithTag(Tags.enemyTag);
float shortestDistance = Mathf.Infinity;
GameObject targetEnemy = null;
foreach (GameObject enemy in enemies)
{
float distance = enemy.GetComponent<Enemy>().agent.remainingDistance;
if (distance < shortestDistance && Vector3.Distance(transform.position, enemy.transform.position) <= range * 10 + rangeBuff)
{
shortestDistance = distance;
targetEnemy = enemy;
}
}
if (targetEnemy != null)
{
target = targetEnemy.transform;
}
else
{
target = null;
}
}
// a lot of other stuff
Enemy.cs:
public class Enemy : MonoBehaviour, IPooledObject
{
public EnemySplit[] splits;
public bool cameFromSplit = false;
public EnemyBlueprint enemy;
public float health;
public float speed;
[HideInInspector]
public float slow;
public Image healthBar;
public List<Tower> towersSlowing = new List<Tower>();
[HideInInspector]
public NavMeshAgent agent;
private GameObject end;
public bool stunned;
void Awake()
{
agent = GetComponent<NavMeshAgent>();
end = GameObject.FindGameObjectWithTag(Tags.endTag);
}
public void OnSpawned()
{
slow = 1f;
speed = enemy.startSpeed;
health = enemy.startHealth;
splits = enemy.splits;
agent.speed = speed * 10;
agent.updateUpAxis = false;
agent.updateRotation = false;
agent.SetDestination(end.transform.position);
if (cameFromSplit)
{
StartCoroutine(CameFromSplit());
}
foreach (EnemyReinforcements re in enemy.reinforcements)
{
StartCoroutine(HandleReinforcement(re.enemyIndex, re.rate, re.count));
}
InvokeRepeating("UpdateHealth", 0f, 0.1f);
InvokeRepeating("UpdateCheck", 0f, 0.2f);
//StartCoroutine(LateStart());
transform.rotation = Quaternion.Euler(90, 0, 0);
}
// a lot of other stuff
我正在使用对象池来召唤我的敌人。因此,将OnSpawned()视为Start()。
更新: 将我的定位代码更改为
if (enemy.GetComponent<Enemy>().agent.pathPending) distance = Vector3.Distance(enemy.transform.position, transform.position);
else { distance = enemy.GetComponent<Enemy>().agent.remainingDistance; }
它似乎是针对最近的敌人。所以,敌人仍在等待中……??