Jumping on slopes makes the player to jump higher than expected.

The player jumps always the same in the ground. But when it’s running in a slope and it jumps at the same time, it jumps more than what it should be. Is there any way to fix that?

        if (m_Grounded && jump)
        {
            m_Grounded = false;
            m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
        }

7904482--1007296--jump bug slope.gif

Not enough information, you only post a snippet completely out of any context. It’s like asking about the contents of your house and letting us see through a keyhole. :wink:

The physics system isn’t “jumping” and it’s not aware of “Slopes” either, it’s adding the force you ask, as simple as that.

So guesswork. Likely your grounded/jump flags are different and maybe you’re adding forces per-frame which make it frame-rate dependent.

The return question would be, what debugging have you done to narrow it down?

Ok, so m_Grounded is a bool that depends on if you are touching the ground or not.
Jump is another bool variable that is true when you press the space bar and false when it’s not pressed.

So I add the force once, and the thing is that when you run your velocity in the Rigidbody2D.y is 0, but in a slope it increases. Then if you press the space bar you jump more than what is expected.

To run I use m_Rigidbody2D.velocity = new Vector2(speed, m_Rigidbody2D.velocity.y)

If instead of putting m_Rigidbody2D.velocity.y, I put 0f, the player can’t jump. So now, can I do something to fix that or you need more info?

Joining in on MelvMays guessing session:

Have you Debug.Logged the force you added? I can image the m_grounded flag stays true for two or three frames because you’re still close to the ground while jumping. If that’s the case could implement some cooldown time

If I’m wrong and it’s actually the y-component while walking up a slope, you can use ForceMode.velocityChange and calculate the difference between the actual y-velocity and the desired y-velocity for jumping and add that

That happens because while going up the slope, the character develops some vertical velocity as well (rb.velocity.y > 0). So, by adding that jump force the jump gets “stronger”.

The fix should be simply, force vertical velocity to 0 everytime the character jumps.

if (m_Grounded && jump)
{
            // <rb.vel.x, rb.vel.y> - <0, rb.vel.y> = <rb.vel.x, 0>
            m_Rigidbody2D.velocity -= Vector2.up * m_Rigidbody2D.velocity.y;  

            m_Grounded = false;
            m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
}

Note that something like this also happens if you let go the horizontal input (e.g. AD, left/right arror), the character do a little (but very annoying) “jump”. Obviously, this depends on the gravity value and the horizontal velocity of the character. In order to fix this you need to stick your character to the ground in some way.