繁体   English   中英

为什么我的 2D Unity 游戏中的跳跃帧率不独立

[英]Why Isn't My Jumping Frame Rate Independent in My 2D Unity Game

出于某种原因,我根据帧速率跳到不同的高度。 为什么即使我使用增量时间(尝试)使其帧速率独立,也会发生这种情况。 如果您需要知道,这是二维的。

void Jump()
{
    // Set Delta Time(Time Between Frames)
    float dT = Time.deltaTime;
    // Counting In Seconds
    secondForGravity += dT;
    // Check For Input and Jump
    if (canJump && Input.GetKeyDown(KeyCode.Space))
    {
        // Add Jump Height to Velocity
        velocity.y += jumpHeight;
        // Reset Can Jump
        canJump = false;
        // Resets Second For Gravity to 0 so You Can't Fall 
        secondForGravity = 0;
    }
    // Fall With Gravity
    if (!canJump)
    {
        if(velocity.y > 0)
        {
            // Rising Metres Per Second * Per Second & Make it Frame Rate Independent
            velocity.y -= riseGravity * secondForGravity * dT;
        }
        else if(velocity.y < 0)
        {
            // Falling Metres Per Second * Per Second & Make it Frame Rate Independent
            velocity.y -= fallGravity * secondForGravity * dT;
            // Sets Velocity.y To Max Gravity if Exceeding Max Gravity
            if (velocity.y < -maxGravity)
                velocity.y = -maxGravity;
        }
        else
        {
            // Rising Metres Per Second * Per Second & Make it Frame Rate Independent
            velocity.y -= riseGravity * secondForGravity * dT;
        }
    }
}

void Move()
{
    // Move
    rb.AddForce(velocity, ForceMode2D.Force);
}

我想知道我是否可以修复它。

你用secondForGravity做什么似乎没有意义。 随着每帧secondForGravity的增加,重力的影响会越来越强。

在我看来,好像您应该将其完全取出并乘以 deltaTime,它表示自上一帧以来经过的秒数(即1 * deltaTime应该每秒出现 1,除了轻微的浮点不精确)。

我通过将velocity添加到我当前的 position 并在Move() function 中使用此代码找到了解决方案:

rb.MovePosition(velocity + new Vector2(transform.position.x, transform.position.y));

而不是这段代码:

rb.AddForce(velocity, ForceMode2D.Force);

现在,无论我的游戏在角色上运行的帧速率是多少,它都会以恒定的速度移动。 我还在用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM