Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question When to modify rigidbody velocity ?

Discussion in 'Physics' started by Azsteak, Jan 14, 2023.

  1. Azsteak

    Azsteak

    Joined:
    Sep 13, 2018
    Posts:
    3
    Hi everyone !

    I'm currently making a character controller entirely using a RigidBody.
    It works really well, but now I would want to be able to cancel it's speed. Currently I update its velocity based on Inputs and gravity during FixedUpdate, I have disabled gravity on the rigidbody so that I can control when it is applied.
    Problem is, when I try to set the rigidbody velocity to zero, my controller can still move a bit, although really slowly.

    My function currently look something like this :
    Code (CSharp):
    1. private void FixedUpdate() {
    2.     newVelocity = (forwardMovement * Input.GetAxisRaw("Vertical") + rightMovement * Input.GetAxisRaw("Horizontal")) * moveForce;      
    3.  
    4.     // Make acceleration less effective at higher speeds
    5.     newVelocity = newVelocity / (1 + rb.velocity.magnitude) * accelerationRate;
    6.  
    7.     rb.AddForce(newVelocity, ForceMode.Acceleration);
    8.  
    9.     if (applyGravity)
    10.         rb.AddForce(Physics.gravity);
    11.  
    12.     rb.velocity = Vector3.zero;
    13. }
    With the last line, my rigidbody should not be able to move, but it does.
    Doest it mean the Rigidbody move as soon as AddForce is called ? I would think it only move during the internal physic update step in the Physic lifecycle.

    Hope someone will have an idea as to why it happens.
    Thanks in advance !
     
  2. Azsteak

    Azsteak

    Joined:
    Sep 13, 2018
    Posts:
    3
    Well, I just found a way around that.
    I currently reduce the velocity based on a factor, I can use this factor to also reduce gravity and move force.

    That's all folks
     
  3. lightbug14

    lightbug14

    Joined:
    Feb 3, 2018
    Posts:
    446
    The last line means that the current velocity is forced to zero. However, that doesn't mean "the body should not be able to move". In this case, the accumulated force (rb.AddForce(Physics.gravity)) affects the body during the simulation state.

    The body won't move instantly since AddForce only affects some internal field. Btw, you can get the accumulated force with this (2022.2):
    https://docs.unity3d.com/2022.2/Documentation/ScriptReference/Rigidbody.GetAccumulatedForce.html

    I guess you could reset this force by applying an opposite force to the body:
    Code (CSharp):
    1. void ResetLinearMovement()
    2. {
    3.        rb.velocity = Vector3.zero;
    4.        rb.AddForce(-rb.GetAccumulatedForce(Time.fixedDeltaTime));
    5. }
    6.