首页 > 解决方案 > 将对象平滑移动到目标 Unity3D

问题描述

我一整天都在尝试将一个物体从A点平稳地移动到B 点,所以我尝试了LerpMoveTowardsSmoothDamp但每次物体从 A 点消失并立即出现在 B 点!

我尝试了在互联网上找到的所有解决方案,但得到了相同的结果。

你能救我的命并帮我解决这个问题吗?

这是我尝试过的代码:

    transform.position = Vector3.SmoothDamp(transform.localPosition, Destination, ref velocity, Speed);

transform.position = Vector3.Lerp(transform.localPosition, Destination, Speed);

transform.position = Vector3.MoveTowards(transform.localPosition, Destination, Speed);

和更多...

标签: c#unity3d

解决方案


您需要使用 Lerp 不断更新位置。您可以使用协程执行此操作,如下所示(假设 Origin 和 Destination 是已定义的位置):

public IEnumerator moveObject() {
    float totalMovementTime = 5f; //the amount of time you want the movement to take
    float currentMovementTime = 0f;//The amount of time that has passed
    while (Vector3.Distance(transform.localPosition, Destination) > 0) {
        currentMovementTime += Time.deltaTime;
        transform.localPosition = Vector3.Lerp(Origin, Destination, currentMovementTime / totalMovementTime);
        yield return null;
    }
}

你可以调用这个协程:

StartCoroutine(moveObject());

推荐阅读