using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class CarController : MonoBehaviour
[Header("Car Settings")]
public float acceleration = 3000f;
public float brakeForce = 5000f;
public float maxSpeed = 50f;
public float steeringAngle = 30f;
[Header("Wheel Colliders")]
public WheelCollider frontLeftWheel;
public WheelCollider frontRightWheel;
public WheelCollider rearLeftWheel;
public WheelCollider rearRightWheel;
[Header("Wheel Transforms")]
public Transform frontLeftTransform;
public Transform frontRightTransform;
public Transform rearLeftTransform;
public Transform rearRightTransform;
private Rigidbody rb;
private float currentSteerAngle;
private float currentAcceleration;
private float currentBrakeForce;
void Start()
rb = GetComponent<Rigidbody>();
[Link] = 1000f; // Set a realistic mass for the car
void FixedUpdate()
HandleInput();
HandleMotor();
HandleSteering();
UpdateWheels();
private void HandleInput()
// Capture player input for acceleration and steering
currentAcceleration = [Link]("Vertical") * acceleration;
currentSteerAngle = [Link]("Horizontal") * steeringAngle;
// Handle braking
if ([Link]([Link]))
currentBrakeForce = brakeForce;
else
{
currentBrakeForce = 0f;
// Debug input values
[Link]("Vertical Input: " + [Link]("Vertical"));
[Link]("Horizontal Input: " + [Link]("Horizontal"));
private void HandleMotor()
[Link]("Current Acceleration: " + currentAcceleration);
// Apply motor torque to rear wheels only if below max speed
if ([Link] < maxSpeed)
[Link] = currentAcceleration;
[Link] = currentAcceleration;
else
[Link] = 0;
[Link] = 0;
// Apply brake torque to all wheels
[Link]("Brake Force: " + currentBrakeForce);
[Link] = currentBrakeForce;
[Link] = currentBrakeForce;
[Link] = currentBrakeForce;
[Link] = currentBrakeForce;
private void HandleSteering()
// Apply steering angle to the front wheels
[Link] = currentSteerAngle;
[Link] = currentSteerAngle;
// Debug steering angle
[Link]("Steering Angle: " + currentSteerAngle);
private void UpdateWheels()
// Update visual wheel transforms to match physics wheels
UpdateWheelPose(frontLeftWheel, frontLeftTransform);
UpdateWheelPose(frontRightWheel, frontRightTransform);
UpdateWheelPose(rearLeftWheel, rearLeftTransform);
UpdateWheelPose(rearRightWheel, rearRightTransform);
private void UpdateWheelPose(WheelCollider collider, Transform
transform)
{
// Sync the wheel position and rotation with the collider
Vector3 pos;
Quaternion quat;
[Link](out pos, out quat);
[Link] = pos;
[Link] = quat;