- Home /
Apply force to rigidbody based on child object acceleration causes jitter
I'm attempting to simulate a situation where a child object's movement in the z axis applies force to the parent rigidbody to give a realistic simulation of momentum - think of a rider on a bicycle that's balanced and stationary throwing their weight backwards and forwards and causing the bike to roll back and forward under them in response.
(in FixedUpdate):
rp = childObject.transform.localPosition;
var rMov = rp.z - rpOld.z;
var rSpeed = rMov / Time.fixedDeltaTime;
var rAcc = (rSpeed- rSpeedOld) / Time.fixedDeltaTime;
rb.AddRelativeForce(Vector3.forward * (-rAcc * 100));
rpOld = childObject.transform.localPosition;
rSpeedOld = rSpeed;
This produces strange effects with jitter and off-axis or rotational forces applied to the rigidbody.
Using the speed of the child object (rSpeed) instead of it's acceleration this doesn't happen and the force is applied smoothly and in the correct direction - however momentum is not conserved properly like this.
Interpolation on/off on the rigidbody has no effect.
Answer by mjc33 · Mar 06, 2020 at 03:44 AM
I managed to solve this issue, in case it helps anyone else - I believe it's caused by a limited lack of samples related to the fixedupdate rate, which becomes more significant (producing spikey data) as you add more time derivatives,
Fix was to use an average of the rAcc over the previous 16 fixedupdates, which smooths things out nicely
private List<float> rAccs = new List<float>();
private float average = 0;
..
rAccs.Add(rAcc);
if (rAccs.Count > 16) {
rAccs.RemoveAt(0);
average = rAccs.Average();
}
else { average = 0; }