3
votes


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);
}
3

3 Answers

2
votes

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().

2
votes

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.

1
votes

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);
}