【发布时间】:2019-06-26 20:13:01
【问题描述】:
我正在尝试将 2d 对象从 a 点移动到 b 点而不改变其统一旋转
我尝试使用Vector2.Lerp(),但它不起作用
Vector2 pointB = new Vector2(20, 10);
Vector2.Lerp(transform.position, pointB, 3F);
代码应该在 3F 秒内将对象从点 a 移动到 b
【问题讨论】:
我正在尝试将 2d 对象从 a 点移动到 b 点而不改变其统一旋转
我尝试使用Vector2.Lerp(),但它不起作用
Vector2 pointB = new Vector2(20, 10);
Vector2.Lerp(transform.position, pointB, 3F);
代码应该在 3F 秒内将对象从点 a 移动到 b
【问题讨论】:
首先,Vector2.Lerp 不会更改第一个参数的值。如果您想以这种方式更改变换的位置,您需要将新值分配给transform.position。
其次,您需要每帧更新一次变换的位置,以保持变换平稳移动。
第三,Vector2.Lerp 只会在开始和结束之间产生位置,t 在 0 和 1 之间。这个t 应该与自此运动开始以来经过的时间与将要经过的时间的比率有关完成动作。
这对coroutine 很有用:
private IEnumerator GoToInSeconds(Vector2 pointB, float movementDuration)
{
Vector2 pointA = transform.position;
float timeElapsed = 0f;
while (timeElapsed < movementDuration)
{
yield return null;
timeElapsed += Time.deltaTime;
transform.position = Vector2.Lerp(pointA, pointB, timeElapsed/movementDuration);
}
}
下面是Start的使用示例:
void Start()
{
Vector2 pointB = new Vector2(20, 10);
StartCoroutine(GoToInSeconds(pointB, 3f));
}
【讨论】:
Mathf.SmoothStep(0, 1, timeElapsed/movementDuration)