Unity rigidbody constant velocity

10,777

Solution 1

Note that the physics engine is updated at a different interval than other basic game logic.

In particular, the state of the Rigidbody is updated once per call to FixedUpdate(), thus if you want to override any results of the physics engine you probably want to do it inside your own FixedUpdate(), instead of Update().

Solution 2

If you really want the object to have constant speed no matter what, then you don't want it to be affected by collisions and gravity. In this case, you should check Kinematic checkbox in rigidbody's properties. This way, you'll be able to move the object's transform from the script, and the object's location won't be affected by anything else.

Solution 3

Aside from what everybody has already told you I would add that if you want to keep a constant speed on a particular direction (X axis in your case) a more correct code would be :

void FixedUpdate () {
    // We need to keep the old y and z component if we want the object to still be affected by gravity and other things
    rigidbody.velocity = new Vector3(5.0f , rigidbody.velocity.y, rigidbody.velocity.z);
}
Share:
10,777

Related videos on Youtube

Dan
Author by

Dan

Updated on September 14, 2022

Comments

  • Dan
    Dan over 1 year


    I have an object which is affected by gravity and collision effects. How can I make it to maintain a constant velocity on the X axis?
    I have something like that:

    void Update () {        
         rigidbody.velocity = 5 * new Vector3(1f,0f,0f);
    }
    
  • Kay
    Kay over 11 years
    +1 Another approach might be to apply a force just once. Then the physics engine should maintain a constant velocity as long as it is perpendicular to gravity and you save the FixedUpdate code.
  • Dan
    Dan over 11 years
    If I apply a force just once my object will stop soon because of collisions.