-帮助-如何找到敌人沿着路径的距离?

时间:2019-03-10 23:08:50

标签: c# unity3d

我目前正在从事塔防游戏,我有一个沿路径移动的敌人,路径的每个角都是一个“节点”,这就是我用来创建路径的对象。我发现了一种通过累加每个节点之间的距离来查找路径有多长的方法。但是我无法弄清楚如何找到敌人沿着这条路有多远,这是我当前的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveAlongPath : MonoBehaviour
{

    private GameObject[] pathObjects;

    private int currentWayPoint = 0;
    GameObject targetWayPoint;

    private float speed = 2f;

    public float pathDistanceTotal = 0;

    // Start is called before the first frame update
    void Start()
    {
        //Find all of the nodes on the map
        FindNodes();
        transform.position = pathObjects[0].transform.position;
        PathDistance();
    }

    // Update is called once per frame
    void Update()
    {
        //Check if we can move somewhere
        if(currentWayPoint < pathObjects.Length)
        {
            if(targetWayPoint == null) 
                targetWayPoint = pathObjects[currentWayPoint];
            move();
        }
    }

    void FindNodes()
    {
        pathObjects = GameObject.FindGameObjectsWithTag("PathPoint");
    }

    void move()
    {
        transform.right = Vector3.RotateTowards(transform.right, targetWayPoint.transform.position - transform.position, 0, 0.0f);

        transform.position = Vector2.MoveTowards(transform.position, targetWayPoint.transform.position, speed * Time.deltaTime);

        if(transform.position == targetWayPoint.transform.position)
        {
            currentWayPoint++;
            targetWayPoint = pathObjects[currentWayPoint];
        }
    }


    //Find The Path Distance
    void PathDistance()
    {
        int i;
        for (i = 0; i < (pathObjects.Length - 1); i++)
        {
            float dis = Vector2.Distance(pathObjects[i].transform.position, pathObjects[i + 1].transform.position);
            pathDistanceTotal += dis;
        }


    }

}

1 个答案:

答案 0 :(得分:0)

您可以简单地将所有先前的节点相加到一个总数上以获得距离,也可以在单元在节点之间移动时将其相加。

我要说的是,为了管理这种运动,您可能很难通过仅执行pathObjects = GameObject.FindGameObjectsWithTag("PathPoint");来管理节点,最好有一个包含这些列表的类,在这种情况下您可以将它们编入索引。当前,您不知道节点的顺序是否正确。

然后,您可以执行与PathDistance中相同的for循环,但是只要达到当前路径索引就可以尽早退出,最后将单位的距离添加到所测量的最后一个节点。