How to calculate acceleration and velocity of constrained objects
I'm stuck on trying to build a manual accelerometer/speedometer script for objects that are using ParentConstraint component to move around (no RigidBody)
I'm running into issues with the acceleration part, with the numbers jumping around wildly, I suspect it is something related to Update vs Fixed Update, and/or Time.deltaTime vs fixedDeltaTime. Or maybe I just need to average over more frames? Or maybe my math is messed up...
Here's sorta what I have so far, any help would be amazing.
void Update()
{
///////////// VELOCITY ////////////
Velocity = (currentPosition - prevPosition) / Time.fixedUnscaledDeltaTime;
CurrentSpeedAvg = ( Mathf.Abs(Velocity.x ) + Mathf.Abs(Velocity.z) ) / 2 ;
//This part seems to work fine, I'm getting the average velocity of x and z axis.
///////////// ACCELERATION ////////////////
CurrentAcceleration = (Velocity - prevVelocity) / Time.fixedUnscaledDeltaTime;
CurrentAccelerationCoef = ((Mathf.Abs(CurrentAccelerationLocal.x) + Mathf.Abs(CurrentAccelerationLocal.z)) / 2); // this jumps around wildly
CurrentAccelerationSmoothed = Mathf.Lerp(CurrentAccelerationCoef, pastAccelerationCoef, .5f); //Here I was just attempting to smooth it out but it's still unusable
//////////////// STORED FOR NEXT FRAME //////////////
prevPosition = currentPosition;
prevVelocity = Velocity;
pastAccelerationCoef = CurrentAccelerationCoef;
}
Answer by jason416 · Dec 19, 2019 at 06:33 PM
So I was able to get some usable data by doing pretty heavy filtering using an animation curve and mathF.smoothDamp (smoothDamp seems much better for this than Lerp)
But I still think the initial calculation isn't being done right because there's so much noise in the calculation. If anyone has a better solution please share.
In your question, what is CurrentAccelerationLocal
? Is it equal to CurrentAcceleration
? And what is the meaning of CurrentAccelerationCoef
? Should you square x and z values from CurrentAcceleration
?