2D car physics works unstable

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Uralkemal

Hello I want to implement marco’s car physics to Godot. Braking and accelarating works but steering the car makes it turn weird and the car spins around very fast.

func physics(delta):
	var sn = sin(heading);
	var cs = cos(heading);
velocity_c.x = cs * velocity.x + sn * velocity.y;
velocity_c.y = cs * velocity.y - sn * velocity.x;


var axleWeightFront = mass * (axleWeightRatioFront * gravity - weightTransfer * accel_c.x * cgHeight / wheelBase);
var axleWeightRear = mass * (axleWeightRatioRear * gravity + weightTransfer * accel_c.x * cgHeight / wheelBase);


var yawSpeedFront = cgToFrontAxle * yawRate;
var yawSpeedRear = cgToRearAxle * yawRate;


var slipAngleFront = atan2(velocity_c.y + yawSpeedFront, abs(velocity_c.x)) - sign(velocity_c.x) * steerAngle;
var slipAngleRear  = atan2(velocity_c.y + yawSpeedRear,  abs(velocity_c.x));

var tireGripFront = tireGrip;
var tireGripRear = tireGrip * (1.0 - inputebrake * (1.0 - lockGrip));

var frictionForceFront_cy = clamp(-cornerStiffnessFront * slipAngleFront, -tireGripFront, tireGripFront) * axleWeightFront;
var frictionForceRear_cy = clamp(-cornerStiffnessRear * slipAngleRear, -tireGripRear, tireGripRear) * axleWeightRear;

var brake = min(inputbrake * brakeForce + inputebrake *eBrakeForce, brakeForce);
var throttle = inputthrottle * engineForce;

var tractionForce_cx = throttle - brake * sign(velocity_c.x);
var tractionForce_cy = 0;

var dragForce_cx = -rollResist * velocity_c.x - airResist * velocity_c.x * abs(velocity_c.x);
var dragForce_cy = -rollResist * velocity_c.y - airResist * velocity_c.y * abs(velocity_c.y);

var totalForce_cx = dragForce_cx + tractionForce_cx;
var totalForce_cy = dragForce_cy + tractionForce_cy + cos(steerAngle) * frictionForceFront_cy + frictionForceRear_cy;


accel_c.x = totalForce_cx / mass; 
accel_c.y = totalForce_cy / mass;

accel.x = cs * accel_c.x - sn * accel_c.y;
accel.y = sn * accel_c.x + cs *accel_c.y;

velocity.x += accel.x * delta;
velocity.y += accel.y * delta;

absVel = velocity.length();


var angularTorque = (frictionForceFront_cy + tractionForce_cy) *cgToFrontAxle - frictionForceRear_cy * cgToRearAxle;


if abs(absVel) < 0.5 && !throttle:

	velocity.x = 0
	velocity.y = 0
	absVel = 0;
	angularTorque = 0
	yawRate = 0;


var angularAccel = angularTorque / inertia;

yawRate += angularAccel * delta;
heading += yawRate * delta;

rotation = heading
position.x += velocity.x * delta;
position.y += velocity.y * delta;