Rigidbody. The acceleration of free falling object works bad

Hey there! Jumped into Unity just a few days ago and trying to understand the basics.

I wanted to calculate the movement’s velocity of my objects and display it on the scene. When I had done it I noticed that the acceleration of my objects was increasing not very well. I expected the changes of velocity during time like this way: 1.00, 1.25, 1.50, 1.75. 2.00. And in reality I got something like this: 1.00, 1.25. 1.50, 1.25, 1.75, 2.00.

I double-checked the math around Vector3.Magnitude and Time.DeltaTime properties but it works good.
The issue is in position’s changes of my object. Sometimes it doesn’t increase suffiently.

In this simplified case with free falling object my problem still produces:
Create new 3d project → Add 3d Sphere GameObject → Add rigidbody component → Create script for Sphere object

public class SomeScript : MonoBehaviour
{
    UnityEngine.Vector3 previousPositon;
    float time = 0.25f;

    void Start()
    {
        previousPositon = transform.position;
        InvokeRepeating("Do", 0, time);
    }

    private void Do()
    {
        var magnitude = (transform.position - previousPositon).magnitude;
        System.Diagnostics.Debug.Write($"magnitude: {magnitude}, velocity: {magnitude / time}");
        previousPositon = transform.position;
    }
}

And in few seconds I got:
magnitude: 20,36554, velocity: 81,46216
magnitude: 22,70029, velocity: 90,80115
magnitude: 21,54272, velocity: 86,1709
magnitude: 23,97562, velocity: 95,90247
magnitude: 22,71991, velocity: 90,87964
magnitude: 25,25085, velocity: 101,0034
magnitude: 23,89713, velocity: 95,5885
magnitude: 26,52618, velocity: 106,1047

Im stuck here and I need your help. Thanks.

Typically, physics steps are calculated 50 times per second or every 0.02 seconds. I don’t know how exactly InvokeRepeating is synchronized, but since 0.25 is not a multiple of 0.02, your Do() function is called probably after 12 physics steps and then after 13 steps, so you can expect a difference of roughly 8 percent between consecutive calls of Do().

try to do the same calculation in FixedUpdate (for every physics frame) or put a counter into FixedUpdate with a modulo operation to call Do() in a different Rate that’s up to your choice. Either way, you should synchronize with the physics loop.

1 Like