【问题标题】:Smooth animation with Vector.moveTowards is not working?Vector.moveTowards 的平滑动画不起作用?
【发布时间】:2019-08-27 04:52:51
【问题描述】:

我曾经问过这个问题,但我仍然没有弄清楚如何解决这个问题。 我正在尝试通过更改 transform.position 来移动 4 个统一游戏对象和 SteamVR 播放器的位置。这真的很好用,但它看起来不太好,因为感觉就像你正在瞬间传送到新位置。

所以我想要的是使用 Vector3.MoveTowards 移动对象。但是我尝试了多种方法,但它不起作用。我有以下不同代码的情况: -> 对象甚至不动 -> 物体瞬间移动

我目前使用的是以下。

更新方法:

private void Update()
{
    if (Condition)
    {
        ZoomIn();
    }
}

放大方法:

private void ZoomIn()
{
    switch (ZoomLevel)
    {
        case 1:
            SetZoomLevel(20, 40);
            ZoomLevel++;
            break;
        case 2:
            SetZoomLevel(40, 60);
            ZoomLevel++;
            break;
        case 3:
            break;
    }
}

SetZoomLevel(运动实际开始的地方,所以问题出在哪里):

private void SetZoomLevel(float height, float distance)
{
    Fade(ObjectToMove1, height, distance);
    Fade(ObjectToMove2, height, distance);
    Fade(ObjectToMove3, height, distance);
    Fade(ObjectToMove4, height, distance);
}

这应该会触发动画

IEnumerator Fade(GameObject teleportObject, float height, float distance)
{
    while (Vector3.Distance(teleportObject.transform.position, new Vector3(0, height, distance)) > 0.001f)
    {
        // Speed = Distance / Time => Distance = speed * Time. => Adapt the speed if move is instant.
        teleportObject.transform.position = Vector3.MoveTowards(teleportObject.transform.position, new Vector3(0, height, distance), 10 * Time.deltaTime);

        yield return null;
    }
}

不知何故,这不起作用。

我希望有人可以帮助我。

提前致谢。

【问题讨论】:

    标签: c# unity3d vector


    【解决方案1】:

    我认为您的 while 声明应该是 if 声明。 我认为您的代码将对象移动到 1 帧 中的最终位置,而不是在多个帧中以平滑的方式进行。对Vector3.MoveTowards 的调用应该发生在不同的帧中。

    您的Fade 方法如下所示:

    void Fade(GameObject teleportObject, float height, float distance)
    {
        if (Vector3.Distance(teleportObject.transform.position, new Vector3(0, height, distance)) > 0.001f)
        {
            teleportObject.transform.position = Vector3.MoveTowards(teleportObject.transform.position, new Vector3(0, height, distance), 10 * Time.deltaTime);
        }
    }
    
    

    【讨论】:

    • 非常感谢您的反应。我已经使用了 Eyap 回答的 StartCoroutine 方法。我使它与 if 语句 aswel 一起工作。谢谢。
    【解决方案2】:

    Fade 是一个协程,但你不要这样称呼它,你应该使用StartCoroutine() 代替。 (见:StartCoroutine)。 你也可以在你的对象上使用 for 循环,这样你就得到了代码:

    private void SetZoomLevel(float height, float distance)
    {
        foreach (GameObject obj in your_objects)
        {
            StartCoroutine(Fade(obj, height, distance));
        }
    }
    

    现在,关于 Fade() 协程,我看不出有什么奇怪的地方,如果它仍然没有按照你的意愿移动,也许可以尝试改变速度值(MoveTowards 的第三个参数中的 10) .

    【讨论】:

    • StartCoroutine 为我做了这件事。非常感谢 !标记为答案:)
    猜你喜欢
    • 2018-03-11
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多