Robin
Robin

Reputation: 21894

Rigidbody not stopping instantly when setting its velocity to 0

I'm trying to make my player's movement snappy, in a 3D environment, using forces. I tried a couple of things, but judging by how my player reacts in-game, I think I'm missing some piece of information.

public Rigidbody rb;

public float acceleration = 500f;
public UnityEngine.ForceMode forceMode = ForceMode.Impulse;

void Update() {
    rb.AddRelativeForce(new Vector3(Input.GetAxis("Horizontal") * acceleration * Time.deltaTime, 0, Input.GetAxis("Vertical") * acceleration * Time.deltaTime), forceMode);
    rb.velocity = Vector3.zero;
}

First of all, how come this code still allows me to move my player around? Resetting the velocity to 0 every frame should prevent it from moving, shouldn't it? I guess the force is still being applied on the subsequent frames even if the velocity is constantly set to 0?

How should I use forces to get really snappy movement, where when I stop pressing UP, the force applied on the Z axis is "stopped"?

Upvotes: 3

Views: 4690

Answers (1)

Erik Overflow
Erik Overflow

Reputation: 2316

Something important to note is the Order of Execution of unity scripts and functionality. The way that physics works is actually a bit more nuanced, and is likely causing your issue.

A quick fix to your problem would likely be something like putting your rigidbody to sleep after setting the velocity to 0:

rb.Sleep();

This ensures that the execution of internal physics update does not affect this rigidbody any further. Typically you do not need need to manually handle Sleep() and WakeUp() for rigidbodies as they are automatically called based on collisions or velocity thresholds, but in this case it will prevent the queued AddForce from impacting the RB after its velocity is zeroed out.

Upvotes: 5

Related Questions