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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Question Momentum with rigidbody movement

Discussion in 'Physics' started by SeanTheDeveloper, Jan 4, 2023.

  1. SeanTheDeveloper

    SeanTheDeveloper

    Joined:
    Aug 2, 2020
    Posts:
    25
    Hi there. I was wondering how you add momentum to a basic rigidbody movement. Does anybody know?
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    Rigidbodies have momentum by default, as per newtonian laws of physics. Just make sure you're not doing something like:
    • Overwriting the velocity directly each frame
    • Moving via non-physical means like transform.Translate
     
  3. SeanTheDeveloper

    SeanTheDeveloper

    Joined:
    Aug 2, 2020
    Posts:
    25
    I am using forces with my controller and it clamps the speed of the rigidbody. I just don't know how to implement it via code
     
  4. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,925
    Rigidbodies have a Drag value. Anything over 0 (and less than 1 -- it's the percent of speed lost) makes them slow down (which is like killing momentum?). But a starting rigidbody has a drag of 0. so Drag isn't your problem unless you changed it.

    You're allowed to play with an object's speed directly.
    transform.GetComponent<Rigidbody>().velocity
    is what the Physics system uses. It's a simple Vector3. To give it a max speed of 8, for example, use this sneaky code. First ignore the math and just see that we can change the speed (on the last line):
    Code (CSharp):
    1. Rigidbody rb = transform.GetComponent<Rigidbody>();
    2. float speed=rb.velocity.magnitude;
    3. if(speed>8) {
    4.   float scaleFactor=8.0f/speed; // note: will be less than 1
    5.   rb.velocity*=scaleFactor;
    6. }