Getting acceleration is glitchy

Hi,

I’m sure this is going to be something dumb, but…
I’m trying to get the acceleration of a rigid body using the following code.

localVelocity = _transform.InverseTransformDirection(_rigidBody.velocity);
GetAcceleration();

private void GetAcceleration()
{
    acceleration = ((localVelocity - oldVelocity) * Time.fixedDeltaTime)*1000.40f ;
    oldVelocity = localVelocity;
}

The object it’s getting the data from is accelerating smoothly at about -0.13 but the numbers I’m getting glitch as sometimes 0 and sometimes -0.25.

(0.02, 0.00, -0.13)acceleration

(0.02, 0.00, -0.13)acceleration

(0.02, 0.00, -0.13)acceleration

(0.02, 0.00, -0.13)acceleration

(0.02, 0.00, -0.12)acceleration

(0.00, 0.00, 0.00)acceleration

(0.03, 0.00, -0.25)acceleration

(0.00, 0.00, 0.00)acceleration

(0.03, 0.00, -0.24)acceleration

(0.01, 0.00, -0.12)acceleration

(0.01, 0.00, -0.12)acceleration

(0.01, 0.00, -0.11)acceleration

(0.01, 0.00, -0.11)acceleration

I think it must be calling the method twice in some frames and skipping some other frames.
I’m not sure how to get it to work.
I’ve tried calling GetAcceleration() in Update and FixedUpdate. I’ve tried multiplying and dividing by Time.deltaTime and Time.fixedDeltaTime but nothing seems to work.

I expected calling it in fixedUpdate would work, but no.

Any ideas?
Thanks in advance.

The derivative method is noisy, so I created a method that worked well for my purposes. I had a thread earlier on that here.

The gist of it is that you back calculate it by calculating Coriolis and centrifugal forces. You then solve for acceleration given that as well as the forces you applied earlier in code. In your case, you don’t have to deal with a mass matrix, so you divide each component in the result by the mass to get the actual acceleration.

1000.40?

It makes sense since the method updates your oldVelocity value each time you call it.
An alternative to that is to calculate acceleration from one physics frame to the next:

public class GetAccelerationScript : MonoBehaviour
{
    Rigidbody _rb;
    Vector3 _oldLocalVelocity;

    Vector3 _acceleration;
    public Vector3 GetAcceleration() => _acceleration;
  
    private void Awake()
    {
        _rb = GetComponent<Rigidbody>();
        StartCoroutine(PostSimulationCoroutine());
    }

    IEnumerator PostSimulationCoroutine()  //<--- Runs after OnCollisionXXX/OnTriggerXXX
    {
        YieldInstruction waitForFixedUpdate = new WaitForFixedUpdate();
        while (true)
        {
            yield return waitForFixedUpdate;

            var localVelocity = transform.InverseTransformDirection(_rb.velocity);
            _acceleration = ((localVelocity - _oldLocalVelocity) * Time.fixedDeltaTime);
            _oldLocalVelocity= localVelocity;
        }
    }
}