Gravity Flipping

So, I’m trying to make a mechanic where I can flip the gravity of my character

Heres the code:

void ChangeGrav()
{
    if (Input.GetKeyDown(KeyCode.E) && !flipped)
    {
        rb.gravityScale = -0.7f;
        flipped = true;
    }

    if (Input.GetKeyDown(KeyCode.E) && flipped)
    {
        rb.gravityScale = 0.7f;
        flipped = false;
    }
}

And for some reason, when flipped = false, the gravity flipping isn’t working. I’ve tested the other way (when flipped = false and gravityScale = -0.7) and for some reason the flipping is working then. Even though the controlling variable (flipped) isn’t set true. Please help!

Your script flips it but then instantly flips it back again. Line 9 should’ve been an ‘else if’. Or a better method:

void ChangeGrav()
{
    if (Input.GetKeyDown(KeyCode.E))
    {
        rb.gravityScale = -rb.gravityScale;
    }
}
1 Like

Also note that you can flip a value like this without knowing what it is by doing:

rb.gravityScale = -rb.gravityScale;

If you don’t need the “flipped” variable beyond this operation, then you can simply do:

    if (Input.GetKeyDown(KeyCode.E))
    {
        rb.gravityScale = -rb.gravityScale;
    }