1

我正在制作一个塔防游戏,其中 NavMeshAgents 穿过从生成点到终点的路径。我的敌人都走同样的路(目前),但他们以不同的速度行进。目前,我的塔总是以离他们最近的敌人为目标。我希望我的塔瞄准需要沿着路径行进最短距离才能到达终点的敌人。

我尝试使用 agent.remainingDistance 但它一直返回 Infinity(根据文档,这意味着代理不知道剩余距离)。

塔.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

敌人.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; }

它似乎瞄准了最近的敌人。所以,敌人还在 pathPending...??

4

0 回答 0