I’m trying to make a car controller using Wheel Collider. I have 4 wheels. And the parent object with rigidbody and box collider. Inside the parent object, I have four objects with Wheel Collider, as well as with Rigidbody and Fixed Joint.
With Fixed Joint, the wheels are attached to the parent object of the machine.
The WheelCollider is configured as follows
The car control script is as follows, it is located on the parent object.
public class CarController2 : MonoBehaviour
{
[Header("Wheel Colliders")]
[SerializeField] private WheelCollider[] frontWheels; // Массив колесных коллайдеров передних колес
[SerializeField] private WheelCollider[] rearWheels; // Массив колесных коллайдеров задних колес
[Header("Wheel Transforms")]
[SerializeField] private Transform[] frontWheelTransforms; // Массив трансформов передних колес
[SerializeField] private Transform[] rearWheelTransforms; // Массив трансформов задних колес
[Header("Car Settings")]
[SerializeField] private float motorForce = 1500f; // Сила двигателя
[SerializeField] private float brakeForce = 3000f; // Сила торможения
[SerializeField] private float maxSteeringAngle = 45f; // Максимальный угол поворота
private float currentMotorForce;
private float currentSteeringAngle;
private float currentBrakeForce;
private void Start()
{
rearWheels[0].steerAngle = 90;
rearWheels[1].steerAngle = 90;
}
private void FixedUpdate()
{
HandleMotor();
HandleSteering();
ApplyBrakes();
UpdateWheelPoses();
}
private void HandleMotor()
{
currentMotorForce = motorForce * Input.GetAxis("Vertical");
foreach (var wheel in rearWheels)
{
wheel.motorTorque = currentMotorForce;
}
}
private void HandleSteering()
{
currentSteeringAngle = maxSteeringAngle * Input.GetAxis("Horizontal");
foreach (var wheel in frontWheels)
{
wheel.steerAngle = currentSteeringAngle + 90;
}
}
private void ApplyBrakes()
{
if (Input.GetKey(KeyCode.Space))
{
currentBrakeForce = brakeForce;
}
else
{
currentBrakeForce = 0f;
}
foreach (var wheel in frontWheels)
{
wheel.brakeTorque = currentBrakeForce;
}
foreach (var wheel in rearWheels)
{
wheel.brakeTorque = currentBrakeForce;
}
}
private void UpdateWheelPoses()
{
UpdateWheelPose(frontWheelTransforms);
}
private void UpdateWheelPose(Transform[] wheelTransforms)
{
currentSteeringAngle = maxSteeringAngle * Input.GetAxis("Horizontal");
for (int i = 0; i < wheelTransforms.Length; i++)
{
wheelTransforms[i].rotation = Quaternion.Euler(0, currentSteeringAngle, 0);
}
}
}
Why is the car not turning, even though the colliders themselves are turning. And when you try to turn the car stops
The problem turned out to be that I turned off the parent object using Fixed Joint, which had locked rotation on all axes in rigidbody, and everything was fixed