Here is my code that moves the car:
using UnityEngine;
public class CarWheelControls : MonoBehaviour {
[SerializeField] WheelCollider frontRight;
[SerializeField] WheelCollider frontLeft;
[SerializeField] WheelCollider BackRight;
[SerializeField] WheelCollider BackLeft;
[SerializeField] Transform frontRightTransform;
[SerializeField] Transform frontLeftTransform;
[SerializeField] Transform backRightTransform;
[SerializeField] Transform backLeftTransform;
public float accerelation = 500f;
public float breakingForce = 300f;
public float maxTurnAngle = 15f;
private float currentAccerelation = 0f;
private float currentBreakForce = 0f;
private float currentTurnAngle = 0f;
private void FixedUpdate(){
//Forward/Reverse acceleration
currentAccerelation = accerelation * Input.GetAxis("Vertical");
//pressing "space" gives currentBreakingForce a value
if (Input.GetKey(KeyCode.Space))
currentBreakForce = breakingForce;
else
currentBreakForce = 0f;
// Apply accerelation on all wheels. Change to front wheel or rear
// wheel drive by deleting fronts or rears :)
frontRight.motorTorque = currentAccerelation;
frontLeft.motorTorque = currentAccerelation;
BackRight.motorTorque = currentAccerelation;
BackLeft.motorTorque = currentAccerelation;
//Wheel stopping
frontRight.brakeTorque = currentBreakForce;
frontRight.brakeTorque = currentBreakForce;
BackRight.brakeTorque = currentBreakForce;
BackLeft.brakeTorque = currentBreakForce;
//Steering
currentTurnAngle = maxTurnAngle * Input.GetAxis("Horizontal");
frontLeft.steerAngle = currentTurnAngle;
frontRight.steerAngle = currentTurnAngle;
//Wheel turning
UpdateWheel(frontLeft, frontLeftTransform);
UpdateWheel(frontRight, frontRightTransform);
UpdateWheel(BackLeft, backLeftTransform);
UpdateWheel(BackRight, backRightTransform);
}
void UpdateWheel(WheelCollider col, Transform trans){
//Wheel collider state
Vector3 position;
Quaternion rotation;
col.GetWorldPose(out position, out rotation);
//Set wheel angle
trans.position = position;
trans.rotation = rotation;
}
I would like it to decrease speed when I'm not accelerating, but I can't figure out how to do it.