I have a gameobject whose position is being changed with below code but velocity’s magnitude is always zero. As much I understand is that velocity is change in direction per time units so there should be a value of velocity here. Any idea what am I missing?
My code is :
void FixedUpdate () {
var ran = Random.RandomRange(0.1f, 0.4f); //gives a random value for x component
go.GetComponent<Rigidbody>().position += new Vector3(ran, 0, 0);
Debug.Log(go.GetComponent<Rigidbody>().velocity.magnitude);//it always shows "0" as output
}
Yeah, so while the Rigidbody is technically moving, you aren’t using forces to move it. You are setting it’s position a bunch of times. The Rigidbody itself just thinks it’s being teleported many times. Sooo… you could calculate the velocity yourself (like you said, distance over time), or you could use the Rigidbody’s functions like AddForce and such to actually have it’s velocity update over time. If you have the behavior you want already, and you just need the velocity, you’d probably want to calculate it yourself. Hopefully that helps!
Velocity is managed by the physics engine. It expresses the direction and distance per unit time (1 second) that the physics engine is currently applying. Since the movement of the object is not managed by the physics engine, the physics engine isn’t moving the object and so the velocity it is applying is zero.
If you use forces on the Rigidbody, there will subsequently be a velocity, but then you shouldn’t be changing position yourself as that confuses the physics engine.
Get the direction of the last position towards to the position. V3 new- last. Then divide by Time.fixedDeltaTime. Then you subtract the rigidbody velocity from that V3. Then you can AddForce(V3 new velocity, Forcemode). This is only done in the fixed update message. And the ForceMode is VelocityChange. That is how you can calculate the change in velocity and then you can apply something based on that. You can multiply the velocity for example if your releasing a rigidbody say from a fishing pole that is controlled by an animator.
Get the direction of the vector in the fixed updated message. Divide that vector3 by Time.fixedDeltaTime Then subtract the rigidbody velocity (if any) then you can AddForce(direction, ForceMode.VelocityChange) bingo that is it. You could multiply the direction by some number to launch it more or subdue it.