【发布时间】:2020-10-27 18:39:07
【问题描述】:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveOnCurvedLine : MonoBehaviour
{
public LineRenderer lineRenderer;
public GameObject objectToMove;
public float speed;
public bool go = false;
public bool moveToFirstPositionOnStart = false;
private Vector3[] positions;
private Vector3[] pos;
private int index = 0;
// Start is called before the first frame update
void Start()
{
pos = GetLinePointsInWorldSpace();
if (moveToFirstPositionOnStart == true)
{
objectToMove.transform.position = pos[index];
}
}
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()
{
objectToMove.transform.position = Vector3.MoveTowards(objectToMove.transform.position,
pos[index],
speed * Time.deltaTime);
if (objectToMove.transform.position == pos[index])
{
index += 1;
}
if (index == pos.Length)
index = 0;
}
}
即使我将速度值设置为 1000 甚至 10000,速度也会更快,但不是那么快或不是很快。
可变数组位置共有 1157 个位置。所以在没有这么多位置的情况下快速移动有点问题,在其他情况下可能有 5000 个或更多位置,具体取决于 linerenderer 线的长度。
但我在一些 youtube 演示中看到汽车和物体在曲线或很长的线上快速移动。
【问题讨论】:
-
您的移动速度看起来取决于您的点之间的距离。即使您的移动速度非常快,您最多只能在一个更新周期内从一个点移动到另一个点。没有逻辑可以说,例如,如果您每次更新移动 100 英里并且您的点之间的距离为 1 英里,则继续到下一个点,直到 100 英里已经行进。因此,我认为这可能会影响事情。如果您限制每帧的停止次数 (
pos),那么您的速度有多快并不重要。 -
@ps2goat 如果我跳过某些位置?我的意思是,如果有 1000 个位置,但我只会在每 10 个位置索引上移动,例如从位置索引 0 开始,然后跳转到索引 10,然后跳转到 20....1000 它会保持曲线效果移动的平滑度吗?会更快吗?或者它看起来像物体从一个地方跳到另一个地方?
-
@ps2goat 那么根据逻辑,你如何在游戏中让飞机、汽车或宇宙飞船在航路点中移动,包括长区域轨道中的弯曲航路点?例如无尽的轨道游戏运动或自动在天空中移动的飞机?
-
这取决于您使用的规模。如果您有一个我可以查看的工作项目示例,我可以获得更好的上下文。根据用户所看到的,对象可能不会击中每个点。但是该对象将在某种程度上遵循路径。对于轨道上的火车之类的情况,您不会想全速绕过拐角,但对于飞机之类的情况可能并不那么明显。