Search Unity

Questions on rigidbody.velocity

Discussion in 'Physics' started by StrawberryStudios, Jun 16, 2019.

  1. StrawberryStudios

    StrawberryStudios

    Joined:
    Jun 14, 2019
    Posts:
    7
    Imagine I have a single gameobject in a scene and I add a script containing something like this:

    void FixedUpdate() {

    rigidbody.velocity = new Vector3(10,0,0);
    }

    Doing this I ensure that the velocity is constant at 10 units/s. What I notice however is that the time it takes for the gameobject to travel 10 units is not actually 1 second but rather 1.43s or so (this I checked with Time.deltaTime). This is true even though I have set drag to 0 and turned of gravity. What is causing the gameobject to move slower than 10 units/s? What other part of the physics engine is at play here?

    Also, in the unity documentation it states that it is not recommended to directly modify the velocity vector. Is this true even in a simple example like the one above (where there are no collisions)? Or when is this not advised?
     
    siddharth3322 likes this.
  2. Edy

    Edy

    Joined:
    Jun 3, 2010
    Posts:
    1,497
    Doing that means that both you and the physics engine are modifying the velocity and interfering each other.

    When the internal physics update occurs it uses your velocity as "starting state", then applies all other forces and interactions affecting the rigidbody. That results in a new velocity (different than yours) that will be used for computing the new position for that physics update.

    If you want to apply a specific velocity to the rigidbody you should do so with Rigidbody.AddForce and ForceMode.VelocityChange. This applies an instant velocity change to the rigidbody while applying all other forces and interactions.

    This will work, as it "removes" the current velocity of the rigidbody and applies yours:
    Code (CSharp):
    1. void FixedUpdate
    2. {
    3.     rigidbody.AddForce(new Vector3(10,0,0) - rigidbody.velocity, ForceMode.VelocityChange);
    4. }
     
  3. Ruchir

    Ruchir

    Joined:
    May 26, 2015
    Posts:
    84
    This still doesnt Work :(
     
  4. Ruchir

    Ruchir

    Joined:
    May 26, 2015
    Posts:
    84
    Gravity is still there
     
  5. Edy

    Edy

    Joined:
    Jun 3, 2010
    Posts:
    1,497
    Turn it off
     
    Ruchir likes this.
  6. Ruchir

    Ruchir

    Joined:
    May 26, 2015
    Posts:
    84
    is there a way that my rigidbody doesn't Get any other velocity other than what I assign ,because in one frame it can gain enough velocity to make things go the wrong way (until I can change it in Fixed Update) Without Making it kinematic (as I am having a lot of problems making it stable at high speeds due inaccurate capsule casts )?