Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question How can I clamp the Rigidbody velocity?

Discussion in 'Physics' started by dangamer2008, Aug 16, 2023.

  1. dangamer2008


    Aug 16, 2023
    Hello, I want to make a car game, so I made the controls, but there's no friction because I'm using raycasts to calculate the suspension, and I was thinking that I can code that if you're not moving the car, it slowly subtracts the x & z velocity, so it slows down, but the rigidbody keeps subtracting velocity and it becomes negative, so the car moves backwards, I tried to make that it only slows down if the velocity is bigger than 0, but it doesn't works, HELP.
  2. miguel0l


    Nov 10, 2021
    What you could try doing is write an if statement to check if the velocity/values of velocity.x/z are less than or equals to 0. if they are, you can clamp them to a value like 0 and stop the script from decreasing your velocities further. as far as i know, you can't clamp whole vectors so you'll have to clamp the individual values for x and z

    Here's an article you can read about rigidbodies, maybe it'll help you give a gist of what else you could try doing with rigidbodies to help out with your car game!
  3. arkano22


    Sep 20, 2012
    Multiply instead of subtract. That is, instead of doing:

    Code (CSharp):
    1. velocity = velocity - someSmallValue;
    Code (CSharp):
    1. velocity = velocity * someValueSmallerThanOne;
    For instance, if you multiply your velocity by 0.99, it will be reduced by 1% every frame. If you multiply by 0.95, it will be reduced by 5%, etc.

    Once your velocity reaches 0, you get 0 * someValueSmallerThanOne which is 0.