简体   繁体   中英

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

For some reason I jump at a different height according to frame rate. Why is this happening even though I am using delta time to(try) make it frame rate independant. This is in 2D in case ye needed to know.

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

I was wondering if there was anyway I could fix it.

What you're doing with secondForGravity doesn't seem to make sense. The effect of gravity will become stronger and stronger as secondForGravity is increased each frame.

It looks to me as if you should take it out completely and just multiply by deltaTime which represents the fraction of a second that passed since the previous frame (ie 1 * deltaTime should come out to 1 per second apart from slight floating point imprecision).

I found a solution by adding velocity to my current position and using this code in the Move() function:

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

Instead of this code:

rb.AddForce(velocity, ForceMode2D.Force);

Now whatever frame rate my game is running at the character is moving at a constant pace. I am still usuing the

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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