What is the right way to apply gravity?

If i set rigidbody useGravity to off but i want to get the same result as if it was on, how should i apply gravity? Would it be:
rigidbody.velocity += Physics.gravity * Time.deltaTime ?
Or do i have to multiply it by squared deltaTime?

AddForce(Physics.gravity,ForceMode.Acceleration)

Thanks, but is it not completely the same as rigidbody.velocity += Physics.gravity * Time.deltaTime? Would be really nice to finally find out the answer.

If you want to set velocity directly (and I don’t know why would you want to do this - it will generate glitch-y behavior)
than your equation is a correct one.

So the velocity change will be the same but, as i understand, there is a difference to how this velocity will be applied in the next frame? So it is generally advised to not modify velocity directly?

Edit: And for example in a situation where i want to constrain velocity is it ok to do something like that:
if (velocity.y > 15f) velocity = new Vector3(velocity.x, 15f, velocity.z);
Because i don’t really see how it is possible to reliably constrain velocity other than by setting it manually at some point

If you want to constrain velocity than you have to add/sub particular force every FixedUpdate frame.

Vector3 acceleration = (desiredVelocity - body.Velocity) / Time.fixedDeltaTime;
body.AddForce(acceleration,ForceMode.Acceleration)

But remember that this equation will change speed instantly. If you want to smooth it out you need maxAcceleration variable and clamp acceleration accordingly before using it in AddForce

Thanks, that’s a nice solution!

The physics engine computes the velocity based on the different interactions of the rigidbody (AddForce, contacts, friction, etc). Modifying the velocity means overriding the results of the physics solver with yours, which might lead to inconsistencies depending on the situation. Therefore, AddForce should be used by default unless there’s a very good reason to override the velocity.

But does addition like “velocity += something” also count as overriding?

To me, yes. The physics solver has already computed specific velocities (linear and angular) accounting for all the rigidbody interactions and states. These values will also be used as inputs in the next step. Modifying velocity means replacing the computed value with a new one to be used as input in the next step. That counts as overriding.

As an example, imagine some ball-like object rolling on some surface. You could modify its velocity with “velocity += something”, increasing its velocity. However, this means the angular velocity (rolling rate) won’t be coherent the next step as it won’t correspond to the new linear velocity.

Ah, i see now, thanks for explanation!

1 Like