Search Unity

Car Controller Issue

Discussion in 'Getting Started' started by MeProGamer72, Aug 31, 2023.

  1. MeProGamer72

    MeProGamer72

    Joined:
    May 1, 2021
    Posts:
    1
    Hey guys, I've recently wanted to try to make a racing game. I've written up this little script here:


    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class CarController : MonoBehaviour
    4. {
    5.     public WheelCollider frontLeftWheel;
    6.     public WheelCollider frontRightWheel;
    7.     public WheelCollider rearLeftWheel;
    8.     public WheelCollider rearRightWheel;
    9.  
    10.     public Transform visualFrontLeftTire;
    11.     public Transform visualFrontRightTire;
    12.     public Transform visualRearLeftTire;
    13.     public Transform visualRearRightTire;
    14.  
    15.     public float motorForce = 10f;
    16.     public float steerForce = 10f;
    17.  
    18.     private void Update()
    19.     {
    20.         float motor = Input.GetAxis("Vertical") * motorForce;
    21.         float steer = Input.GetAxis("Horizontal") * steerForce;
    22.  
    23.         // Apply motor force to both rear wheels
    24.         rearLeftWheel.motorTorque = motor;
    25.         rearRightWheel.motorTorque = motor;
    26.  
    27.         // Apply steering force to front wheels
    28.         frontLeftWheel.steerAngle = steer;
    29.         frontRightWheel.steerAngle = steer;
    30.  
    31.         // Rotate visual tires based on wheel collider rotation
    32.         RotateTire(visualFrontLeftTire, frontLeftWheel);
    33.         RotateTire(visualFrontRightTire, frontRightWheel);
    34.         RotateTire(visualRearLeftTire, rearLeftWheel);
    35.         RotateTire(visualRearRightTire, rearRightWheel);
    36.     }
    37.  
    38.     // Helper function to rotate visual tires
    39.     private void RotateTire(Transform visualTire, WheelCollider wheelCollider)
    40.     {
    41.         Vector3 position;
    42.         Quaternion rotation;
    43.         wheelCollider.GetWorldPose(out position, out rotation);
    44.         visualTire.position = position;
    45.         visualTire.rotation = rotation;
    46.     }
    47. }
    48.  

    When I attempt to run this it makes the wheels fall in a horizontal position forever. What seems to be the problem?
     
  2. AngryProgrammer

    AngryProgrammer

    Joined:
    Jun 4, 2019
    Posts:
    490
    Try to set the car higher above the ground, and let it fall on it. If still a problem repeat confirm that you have a proper collider around the wheels (there is a special wheel collider).