Recently I began to develop my own car physics in unity and tried to implement Pacejka’s Magic Formula, but I can’t know if I am in the right direction or not cause there are very few data and articles about the Magic Formula.
I read Marco Monster's article and a lot of gamedev discussions.
For now, I only implemented the longitudinal magic formula and it is very unstable even at high speeds
Here is the code:
void HandleLongitudinal(RaycastHit hit)
{
float carLon = Vector3.Dot(rb.velocity, car.transform.forward); //The longitudinal veloctiy of the car
slipRatio = ((angularVelocity * wheelRadius) - carLon) / Mathf.Max(Mathf.Abs(carLon), 0.00001f);
weight = 1500 / 4; //In KG, For now it is a constant
longForce = PacejkaLon(slipRatio * 100, weight * 9.81f / 1000); //The longitudinal Force
rb.AddForceAtPosition(longForce * -transform.right, hit.point); //Adding force in the contact patch area
tractionTorque = longForce * wheelRadius;
totalTorque = wheelTorque - tractionTorque; //For now there is no brake torque or any opposite torques only the traction torque
float wheelInertia = wheelMass * wheelRadius * wheelRadius / 2; //Wheel mass is 70kg and wheel radius is 0.34m
angularAcceleration = totalTorque / wheelInertia;
angularVelocity += angularAcceleration * Time.fixedDeltaTime;
}
Wheel torque is calculated like this:
float gearRatio = 2.66f;
float diffRatio = 3.42f;
float engineTorque = 50;
float wheelTorque = engineTorque * gearRatio * diffRatio * .7f;//.7f is the transmission efficiency
Pacejka Formula:
public float PacejkaLon(float slip, float Fz)
{
C = lonSettings.b0;
D = Fz * (lonSettings.b1 * Fz + lonSettings.b2);
BCD = (lonSettings.b3 * Fz * Fz + lonSettings.b4 * Fz) * Mathf.Exp(-lonSettings.b5 * Fz);
B = BCD / (C * D);
H = lonSettings.b9 * Fz + lonSettings.b10;
E = (lonSettings.b7 * Fz * Fz + lonSettings.b7 * Fz + lonSettings.b8) * (1 - lonSettings.b13 * Mathf.Sign(slip + H));
V = lonSettings.b11 * Fz + lonSettings.b12;
Bx1 = B * (slip + H);
return D * Mathf.Sin(C * Mathf.Atan(Bx1 - E * (Bx1 - Mathf.Atan(Bx1)))) + V;
}
I've printed Pacejka Formula on a graph and it does look like the references I took the formula from this link.
The video
As you can see the slip ratio graph is oscillating too much, and worth mentioning that the engine torque is constant in the video, I tried to increase it over time but still the same results.
Is this the kind of behavior that the Pacejka Fourmla do or not? If not, could you please guide me in the right direction because now I am a bit lost and don't know what is wrong :(
Sorry for taking your time <3