Home > database >  Weird rb.velocity.y
Weird rb.velocity.y

Time:10-28

When I'm moving left or right rb.velocity.y changes to weird numbers. How can I get rid of this? I want to change the gravity when player is jumping and because of this bug it changes even if player is moving left and right.

    void FixedUpdate(){

        isGrounded = Physics2D.BoxCast(coll.bounds.center,coll.bounds.size, 0, Vector2.down, .1f,WhatIsGround);

        rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);

        if(jumped){
            rb.AddForce(Vector2.up * jump, ForceMode2D.Impulse);
            jumped = false;
        }

        if(rb.velocity.y < 0){
            rb.gravityScale = fallMultiplier;
        }
        else if(rb.velocity.y > 0 && !(Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.UpArrow))){
            rb.gravityScale = lowJumpMultiplier;
        }
        else{
            rb.gravityScale = 1f;
        }  
    }

CodePudding user response:

Both floating point calculations and Unity physics aren't precise. When your Rigidbody is moving, the gravity is trying to push it into the ground collider, while collision detection is pushing it upwards. This results in tiny oscillations in velocity.

You should never use direct comparison when working with float values. In this case, you need a small threshold to reliably detect the Y velocity direction:

if(rb.velocity.y < -.1f)
{
    rb.gravityScale = fallMultiplier;
}
else if (rb.velocity.y > .1f && !(Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.UpArrow)))
{
    rb.gravityScale = lowJumpMultiplier;
}
else 
{
    rb.gravityScale = 1f;
}  
  • Related