【问题标题】:Unity rope swinging physics algorithm: Player stuck mid-swingUnity 绳索摆动物理算法:玩家在摆动过程中卡住
【发布时间】:2022-12-05 22:16:25
【问题描述】:

我在 Unity (2D) 中实现了以下教程,试图创建一个绳索摇摆平台游戏:https://gamedevelopment.tutsplus.com/tutorials/swinging-physics-for-player-movement-as-seen-in-spider-man-2-and-energy-hook--gamedev-8782

void FixedUpdate() 
{
    Vector2 testPosition = playerRigidbody.position + playerRigidbody.velocity * Time.deltaTime;
    Hooked(testPosition);
}

private void Hooked(Vector2 testPosition)
    {
        Vector2 t = new Vector2(tetherPoint.position.x, tetherPoint.position.y);
        Debug.DrawLine(tetherPoint.position, playerRigidbody.position);
        float currentLength = (testPosition - t).magnitude;

        if (currentLength < tetherLength)
        {
           currentLength = (playerRigidbody.position - t).magnitude * Time.deltaTime;
        }
        else
            currentLength = tetherLength;

        if ((testPosition - t).magnitude > tetherLength)
        {
            Vector2 x = (testPosition - t).normalized;
            testPosition = new Vector2(x.x * currentLength, x.y * currentLength);

            playerRigidbody.velocity = (testPosition - playerRigidbody.position) * Time.deltaTime;
            playerRigidbody.position = testPosition;
        }
    }

它似乎在向下摆动时功能正常,但当玩家开始向上移动时,他们会卡在空中漂浮并且不会掉到弧线的中间。即使从高处掉落,秋千也不会在另一侧将它们推得很高。

当前的半工作解决方案将速度变化乘以 deltaTime,而教程说要除以,但是将“*”更改为“/”只会导致播放器不受控制地弹跳。

我试过检查游戏过程中变量的变化,但我就是想不通为什么它不能正常工作。我认为问题出在我对 C# 的原始伪代码的解释中。

之前已经问过关于同一教程的另一个问题,但不幸的是,用户的实现与我的非常不同:Game rope swing physics acting weird

编辑:自发布以来,我已经更新了代码以使用 AddForce 和 MovePosition,但它仍然是一样的。

playerRigidbody.AddForce((testPosition - playerRigidbody.position) * Time.deltaTime);
playerRigidbody.MovePosition(testPosition);

【问题讨论】:

    标签: unity3d game-physics game-development


    【解决方案1】:

    看起来您正在从一个从 FixedUpdate 调用的方法中使用 Time.deltaTime。您要改用的是Time.fixedDeltaTime

    FixedUpdate 以设定的时间间隔(例如 50fps)被调用以进行物理更新,但常规的 Update 以不同的变化频率被调用(如果您有一台快速的计算机/简单游戏,则每秒调用数百次) .

    Time.deltaTime 用于Update 方法,因此每次调用Update 时它的值可能不同,因为Update 调用之间的时间不同。

    但是,因为每次以相同的间隔调用FixedUpdate,所以Time.fixedDeltaTime 是常量并且(通常)比Time.deltaTime 大得多。您的代码不适用于Time.deltaTime,因为它不代表每次FixedUpdate 调用之间的实际时间差异,但Time.fixedDeltaTime 应该可以。

    作为旁注,你是正确的,你应该乘以时间增量而不是除以。计算位置时应乘以时间增量(例如,对于Vector2 testPosition分配和currentLength计算),但对于计算速度,您应该除以时间增量(因为速度=距离/时间)。

    【讨论】:

    • 我不知道这一点,谢谢您的反馈 :) 将其更改为 fixedDeltaTime 并没有解决问题,玩家角色仍然卡在秋千另一边的一半。
    • 我只是注意到我写的最后一件事是错误的,并且编辑了我的答案——我说你应该总是乘以时间增量——这是不正确的,因为在某一时刻你正在计算速度,它实际上应该是距离/时间.fixedDeltaTime。这有助于解决问题吗?
    猜你喜欢
    • 1970-01-01
    • 2014-10-16
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多