在Vector3的Lerp方法中实现缓入缓出的效果,即在开始和结束的位置采用减速和加速的运动方式。
具体方法如下:
float EaseIn(float t)
{
return t * t;
}
float EaseOut(float t)
{
return 1 - EaseIn(1 - t);
}
Vector3 easeInOutLerp(Vector3 start, Vector3 end, float t)
{
float easeInDuration = 0.2f; // 缓入的时长
float easeOutDuration = 0.4f; // 缓出的时长
float linearDuration = 1 - easeInDuration - easeOutDuration; // 匀速的时长
if (t <= easeInDuration)
{
// 缓入
float tNormalized = t / easeInDuration;
return Vector3.Lerp(start, end, EaseIn(tNormalized));
}
else if (t <= easeInDuration + linearDuration)
{
// 匀速
float tNormalized = (t - easeInDuration) / linearDuration;
return Vector3.Lerp(start, end, tNormalized);
}
else
{
// 缓出
float tNormalized = (t - easeInDuration - linearDuration) / easeOutDuration;
return Vector3.Lerp(start, end, EaseOut(tNormalized));
}
}
void Update()
{
float t = Time.time % 2; // 循环时长为2秒
transform.position = easeInOutLerp(startPosition, endPosition, t / 2f);
}