Unity Lerp 實作講解

夏葉
4 min readJan 19, 2024

這篇文章主要講的是如何利用 Lerp(換成 Slerp 也能運行) 來實現移動。其實有另一個更快捷的方式直接用一些 Tween 插件,例如:LeanTween,DoTween⋯⋯。

利用 Lerp 實現移動可以分成兩大種 Update 和 IEnumerator 方案。

Update()

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;
}
}
}

IEnumerator

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

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

夏葉
夏葉

Written by 夏葉

分享一些關於Unity的小技巧

No responses yet