我试图将2d对象从a点移动到b点,而又不改变其旋转角度
我尝试使用Vector2.Lerp()
,但它不起作用
Vector2 pointB = new Vector2(20, 10);
Vector2.Lerp(transform.position, pointB, 3F);
代码应在3F秒内将对象从a点移动到b点
答案 0 :(得分:1)
首先,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));
}