【发布时间】:2015-07-02 06:10:15
【问题描述】:
我试图制作一个脚本,在两点之间来回移动一个对象。但它只是在无限中飞翔。我整个晚上都试图找出问题所在,但我不知道。 这是代码:
using UnityEngine;
public class MovementBetweenPoints : MonoBehaviour {
public Transform[] keyPoints;
public float speed;
private int currentKeyPoint;
// Use this for initialization
void Start ()
{
transform.position = keyPoints[0].position;
currentKeyPoint = 1;
}
// Update is called once per frame
void Update ()
{
if (transform.position == keyPoints[currentKeyPoint].position)
{
currentKeyPoint++;
}
if (currentKeyPoint >= keyPoints.Length)
{
currentKeyPoint = 0;
}
transform.position = Vector3.MoveTowards(transform.position, keyPoints[currentKeyPoint].position, speed * Time.deltaTime);
}
}
【问题讨论】:
-
尝试使用
Debug.Log来查看它是否会成为您的keyPoints之一。currentKeyPoint的值会改变吗? -
它适用于我的统一,我只是将其插入,确保您在检查器中设置了变换和速度
-
不要使用相等运算符比较浮点数。使用范围或一些 eplison 值,因为取决于帧速率、速度等,transform.position 永远不会等于当前关键点。
-
@Heisenbug 这不完全正确,
Vector3.MoveTowards将说明这一点。根据文档,If the target is closer than maxDistanceDelta/ then the returned value will be equal to targetdocs.unity3d.com/ScriptReference/Vector3.MoveTowards.html -
但是是的,通常我会同意你的看法。
标签: c# unity3d 3d game-physics