Home > Software engineering >  Unity3D, how to enable and disable the gravity of a rigidbody?
Unity3D, how to enable and disable the gravity of a rigidbody?

Time:12-14

Unity3D. How to disable and enable the gravity for one rigidbody? Modifying the property useGravity works, but when we enable the gravity again, it seems the object was falling all the time when the gravity was disabled (starts to fall too fast). How to fix that?

CodePudding user response:

You need to set the velocity of the object back to zero:

void DisableGravity(Rigidbody rb) {
    rb.useGravity = false;
}
void EnableGravity(Rigidbody rb) {
    rb.useGravity = true;
    rb.velocity = Vector3.zero;
}

If you want it to stop moving once gravity is disabled, change DisableGravity to this:

void DisableGravity(Rigidbody rb) {
    rb.useGravity = false;
    rb.velocity = Vector3.zero;
}
  • Related