Home > Software design >  Why Isn't My Jumping Frame Rate Independent in My 2D Unity Game
Why Isn't My Jumping Frame Rate Independent in My 2D Unity Game

Time:04-21

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.

CodePudding user response:

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 (i.e. 1 * deltaTime should come out to 1 per second apart from slight floating point imprecision).

CodePudding user response:

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

  • Related