Jump twice

Hi everyone!

I am new in Unity and I have a question. In my follow script, the cube when in the air, “jump” twice instead one.

Why?

 void FixedUpdate()
    {

        if (Input.GetKeyDown(KeyCode.Space))
        {
            // neste caso a velocidade leva em consideracao a massa do objeto
            // bolaRigidbody.AddForce(new Vector2(0, 1));
            // neste caso a velocidade leva em consideracao a massa do objeto
            // bolaRigidbody.AddForce(Vector2.up, ForceMode2D.Impulse);
            // aqui a massa nao importa. A velocidade sera a mesma.
           
            if (piso == true)
            {
                piso = false;
                bolaRigidbody.velocity = Vector2.up * 5;               
            }
           
        }

    }

    // Collision possui as informacoes sobre a colisao.
    // Colider possui as informacoes sobre os objetos que colidem. Para usar apenas com triggers.
    // Testo se o objeto que tem o metodo de colisao (neste caso, Ball) irá tocar o piso
    void OnCollisionStay2D(Collision2D col)
    {
       
        if (col.gameObject.name == "piso")
        {
           piso = true;

        }
       

    }

FixedUpdate is for doing physics computation. You have to use Update to handle input instead.

Also you want you object to be able to jump only when grounded. One approach to check if your object is grounded is to check its vertical velocity, it’s zero when on the ground (assuming you have only flat floors and no ramps).

1 Like

Thanks for you reply. Can I to use simultaneously Fixed Update and Upstae in same script? Because my object named “Ball” is affected by gravity and mass.

Yes, you can use both FixedUpdate and Update (and any other functions) on the same MonoBehaviour.
You might be interested by this documentation:

The velocity thing might be working most of the times, but dont forget, that an object has 0 velocity at tge peak of his jump too
Cube or spherecasting even detects ramps and stuff too

3 Likes