- 帮助 - 如何找到敌人沿着路径的距离?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了- 帮助 - 如何找到敌人沿着路径的距离?相关的知识,希望对你有一定的参考价值。
我目前正在进行塔防游戏,我有一个沿着路径移动的敌人,轨道的每个角落都是一个“节点”,这是我用来创建路径的。我找到了一种方法,通过将每个节点之间的距离相加来找出路径的长度。但我很难弄清楚如何找到敌人在路径上的距离,这是我目前的代码:
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;
}
}
}
答案
您可以简单地将所有先前的节点添加到总计中以获得距离,或者您可以在单元在节点之间移动时添加它。
我想说,为了管理这种运动,你可能很难通过只做一个pathObjects = GameObject.FindGameObjectsWithTag("PathPoint");
来管理节点,最好有一个包含这些列表的类,在这种情况下你可以索引它们。目前您不知道您的节点是否处于正确的顺序。
然后,您可以在PathDistance中执行相同的循环,但只要在到达当前路径索引时提前退出,最后将单位的距离添加到您测量的最后一个节点。
以上是关于- 帮助 - 如何找到敌人沿着路径的距离?的主要内容,如果未能解决你的问题,请参考以下文章