【发布时间】:2020-10-30 15:15:21
【问题描述】:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class MoveOnCurvedLines : MonoBehaviour
{
public LineRenderer lineRenderer;
public List<GameObject> objectsToMove = new List<GameObject>();
public float speed;
public bool go = false;
public bool moveToFirstPositionOnStart = false;
private Vector3[] positions;
private Vector3[] pos;
private int index = 0;
private bool goForward = true;
private List<GameObject> objectsToMoveCopy = new List<GameObject>();
// Start is called before the first frame update
void Start()
{
objectsToMove = GameObject.FindGameObjectsWithTag("New Prefab").ToList();
pos = GetLinePointsInWorldSpace();
if (moveToFirstPositionOnStart == true)
{
for (int i = 0; i < objectsToMove.Count; i++)
{
objectsToMove[i].transform.position = pos[index];
}
}
StartCoroutine(AddNew());
}
Vector3[] GetLinePointsInWorldSpace()
{
positions = new Vector3[lineRenderer.positionCount];
//Get the positions which are shown in the inspector
lineRenderer.GetPositions(positions);
//the points returned are in world space
return positions;
}
// Update is called once per frame
void Update()
{
if (go == true)
{
Move();
}
}
void Move()
{
for (int i = 0; i < objectsToMoveCopy.Count; i++)
{
Vector3 newPos = objectsToMoveCopy[i].transform.position;
float distanceToTravel = speed * Time.deltaTime;
bool stillTraveling = true;
while (stillTraveling)
{
Vector3 oldPos = newPos;
newPos = Vector3.MoveTowards(oldPos, pos[index], distanceToTravel);
distanceToTravel -= Vector3.Distance(newPos, oldPos);
if (newPos == pos[index]) // Vector3 comparison is approximate so this is ok
{
// when you hit a waypoint:
if (goForward)
{
bool atLastOne = index >= pos.Length - 1;
if (!atLastOne) index++;
else { index--; goForward = false; }
}
else
{ // going backwards:
bool atFirstOne = index <= 0;
if (!atFirstOne) index--;
else { index++; goForward = true; }
}
}
else
{
stillTraveling = false;
}
}
objectsToMoveCopy[i].transform.position = newPos;
}
}
IEnumerator AddNew()
{
WaitForSeconds waitThreeSeconds = new WaitForSeconds(3);
foreach (var objToMove in objectsToMove)
{
yield return waitThreeSeconds;
objectsToMoveCopy.Add(objToMove);
}
}
}
我使用 StartCoroutine 和 AddNew 方法每 3 秒在路点之间移动每个对象。
逻辑:
-
要从列表中移动的第一个对象是从第一个位置开始移动。
-
3 秒后,要从列表中移动的第二个对象将从第一个位置开始移动。
-
目标是让每个对象在他之前的第一个移动对象之后 3 秒后从第一个位置开始移动,所以最后我会让这些对象以 3 秒的间隔移动。
问题:
- 第一个对象在从第一个位置 3 秒后开始移动,然后第二个和第三个对象开始移动,但是从最后一个移动的对象开始,其他已经移动的对象与其他对象合并最后我有一组所有要移动的物体都一起移动。
如果它们反向移动,我想要的行为相同。
【问题讨论】:
-
您能否更详细地解释一下究竟是什么问题。很难理解一切。我唯一得到的是,它们似乎都在延迟 3 秒后移动到同一点,而不是延迟 3 秒后移到彼此?