unity c# hooke's law suspension code example

Example: unity c# hooke's law suspension

void FixedUpdate()
    {
        RaycastHit hit;
 
        for (int i = 0; i < wheelPoints.Length; i++)
        {
            var wheelPoint = wheelPoints[i];
 
            if (Physics.Raycast(wheelPoint.transform.position,
                                -transform.up,
                                out hit,
                                suspensionLength,
                                layerMask))
            {
                // Spring force
                float contactDepth = hit.distance - suspensionLength;  
 
                float springForce = - stiffness * contactDepth;
               
                // Final force or suspension force
                float suspensionForce = springForce;
               
                rigidBody.AddForceAtPosition(transform.up * suspensionForce, wheelPoints[i].transform.position, ForceMode.Force);
                vehicleInAir = false;
            }
            else
            {
                vehicleInAir = true;
            }
        }
    }