這篇文章主要講的是如何利用 Lerp(換成 Slerp 也能運行) 來實現移動。其實有另一個更快捷的方式直接用一些 Tween 插件,例如:LeanTween,DoTween⋯⋯。
利用 Lerp 實現移動可以分成兩大種 Update 和 IEnumerator 方案。
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
moving = true;
}
if (moving)
{
transform.position = Vector3.Slerp(transform.position, position, speed * Time.deltaTime);
if (Vector3.Distance(transform.position, position) < 0.001)
{
moving = false;
}
}
}
public IEnumerator move()
{
float currentSpeed = speed;
while (Vector3.Distance(transform.position, position) > 0.1)
{
transform.position = Vector3.Slerp(transform.position, position, currentSpeed * Time.deltaTime);
currentSpeed += acceleration;
yield return new WaitForSeconds(Time.deltaTime);
}
}
IEnumerator MovementWithSpeed()
{
float currentSpeed = speed;
while (Vector3.Distance(transform.position, position) > 0.1)
{
transform.position = Vector3.Lerp(transform.position, position, currentSpeed * Time.deltaTime);
currentSpeed += acceleration;
yield return new WaitForSeconds(Time.deltaTime);
}
}
IEnumerator MovementWithTime()
{
float currentT = Vector3.Distance(transform.position, position) / time * Time.deltaTime;
while (Vector3.Distance(transform.position, position) > 0.1)
{
transform.position = Vector3.Lerp(transform.position, position, currentT);
yield return new WaitForSeconds(Time.deltaTime);
}
}
Slerp vs Lerp: https://www.faustofonseca.com/tutorial/unity-vector3-lerp-vs-vector3-slerp