created an object and added Rigidbody2d to it. (for gravity)
when printing out the distance traveled in free fall the objects distance seems strange (it sometimes equals 0)
Why?
Doesn’t the Rigidbody2d perform its changes to the object’s position on each frame?
CODE:
void Start() {
D = transform.position;
}
void Update () {
float dist = Vector2.Distance (transform.position, D);
D = transform.position;
Debug.Log("dist "+dist);
}
OUTPUT:
dist 0.003924012
dist 0.007848024
dist 0.2472119
dist 0.04708803
dist 0.05101204
dist 0
dist 0.05493605
Rigid bodies are simulated in discrete steps that are not tied to the framerate (as Update() is). Instead, you can use FixedUpdate which is synchronize with physics steps. Actually you should use FixedUpdate for any over-time work with rigidbodies (applying steady force, reading changes etc). The rigidbody component has an option to smooth (interpolate / extrapolate) the motion of rigidbody and apply the result to gameObject’s transform, so motion appears smooth even when framerate is higher than fixedUpdate rate (which is in most cases). But these interpolations will be physically incorrect (or none if you disable interpolation, that’s where the zeros may be popping up)
In conclusion, use FixedUpdate and Time.fixedDeltaTime to work with RigidBodies
Prefere the FixedUpdate() method for all physics-relative operations.
Here is the description from Unity documentation :
FixedUpdate should be used instead of Update when dealing with Rigidbody. For example when adding a force to a rigidbody, you have to apply the force every fixed frame inside FixedUpdate instead of every frame inside Update.