accelerate

mail@pastecode.io avatar
unknown
csharp
2 years ago
2.0 kB
7
Indexable
 void Acceleration()
    {
        RaycastHit hit;

        for (int i = 0; i < tires.Length; i++)
        {
            if (Physics.Raycast(tires[i].position, -tires[i].transform.up, out hit, offset))
            {
                //world-space direction of the acceleration/braking force.
                Vector3 accelerationDirection = tires[i].forward;

                //acceleration torgue
                if(accelerationInput > 0.0f)
                {
                    //forwar speed of the car (in the firection of driving)
                    float carSpeed = Vector3.Dot(transform.forward, rb.velocity);

                    //normalized car speed
                    float normalizedSpeed = Mathf.Clamp01(Mathf.Abs(carSpeed) / carTopSpeed);

                    //available torque
                    float availableTorque = powerCurve.Evaluate(normalizedSpeed) * accelerationInput;

                    rb.AddForceAtPosition(accelerationDirection * availableTorque, tires[i].position);
                    Debug.DrawLine(tires[i].position, tires[i].position + accelerationDirection * availableTorque, Color.red);
                }                
                else if (accelerationInput < 0.0f)
                {
                    //forwar speed of the car (in the firection of driving)
                    float carSpeed = Vector3.Dot(-transform.forward, rb.velocity);

                    //normalized car speed
                    float normalizedSpeed = Mathf.Clamp01(Mathf.Abs(carSpeed) / carTopSpeed * 0.5f);

                    //available torque
                    float availableTorque = powerCurve.Evaluate(normalizedSpeed) * accelerationInput;

                    rb.AddForceAtPosition(accelerationDirection * availableTorque, tires[i].position);
                    Debug.DrawLine(tires[i].position, tires[i].position + accelerationDirection * availableTorque, Color.red);

                }
                

            }
        }
    }