Simple Car Controller in Unity - A Beginner's Guide

Hello everyone! Today, I'll show you how to create a basic car controller in Unity. Whether you're making a racing game or just need vehicle mechanics in your project, this tutorial will help you get started. Let's dive in! 🚗

What We'll Create

  • A basic car controller with realistic physics
  • Forward/backward movement and turning
  • Braking system
  • Speed calculation
  • Prerequisites

  • Unity (any recent version)
  • Basic understanding of Unity's interface
  • A simple car model (or just a cube to start with)
  • Step 1: Setting Up the Car

  • Create a new 3D object in your scene (you can start with a cube)
  • Add a Rigidbody component to it
  • Create four cylinders for wheels (optional for now)
  • Step 2: Creating the Script

    Create a new script called CarController.cs and add this code:
    using UnityEngine;

    public class CarController : MonoBehaviour
    {
        [Header("Car Settings")]
        public float enginePower = 1000f;
        public float turnSpeed = 50f;
        public float brakePower = 500f;
        
        [Header("Vehicle Physics")]
        public float dragAmount = 0.1f;
        public float angularDragAmount = 0.5f;
        
        private Rigidbody rb;
        private float currentSpeed;

        void Start()
        {
            // Get and setup the rigidbody
            rb = GetComponent<Rigidbody>();
            rb.drag = dragAmount;
            rb.angularDrag = angularDragAmount;
        }

        void FixedUpdate()
        {
            HandleMovement();
            CalculateSpeed();
        }

        void HandleMovement()
        {
            // Forward and backward movement
            float forwardAmount = Input.GetAxis("Vertical") * enginePower * Time.fixedDeltaTime;
            
            // Left and right turning
            float turnAmount = Input.GetAxis("Horizontal") * turnSpeed * Time.fixedDeltaTime;

            // Apply brakes when Space is pressed
            if (Input.GetKey(KeyCode.Space))
            {
                rb.drag = brakePower;
            }
            else
            {
                rb.drag = dragAmount;
            }

            // Apply movement forces
            rb.AddRelativeForce(Vector3.forward * forwardAmount);
            rb.AddRelativeTorque(Vector3.up * turnAmount);
        }

        void CalculateSpeed()
        {
            // Calculate current speed in km/h
            currentSpeed = rb.velocity.magnitude * 3.6f;
        }

        // Useful for UI display of speed
        public float GetCurrentSpeed()
        {
            return currentSpeed;
        }
    }

    Step 3: Understanding the Code

    Let's break down the key components:

    Variables

  • enginePower: Controls how fast the car can accelerate
  • turnSpeed: Determines how quickly the car can turn
  • brakePower: Controls braking strength
  • dragAmount: Affects how quickly the car slows down naturally
  • angularDragAmount: Controls how quickly turning motion stops
  • Movement System

    The script uses Unity's physics system through:
  • AddRelativeForce: Pushes the car forward/backward
  • AddRelativeTorque: Handles turning
  • Rigidbody properties for realistic physics
  • Step 4: Setting Up Controls

    The controls are simple:
  • W or ↑: Accelerate
  • S or ↓: Reverse
  • A/D or ←/→: Turn left/right
  • Space: Brake
  • Step 5: Fine-Tuning

    After attaching the script to your car, you'll need to adjust these values in the Inspector:
  • Start with enginePower around 1000
  • Set turnSpeed to about 50
  • Adjust brakePower to around 500
  • 4. Fine-tune dragAmount (0.1) and angularDragAmount (0.5)

    Tips for Better Results

    1. Weight Distribution: Adjust your car's center of mass in the Rigidbody component
  • Wheel Colliders: For more realistic behavior, consider using Unity's WheelCollider component
  • Physics Material: Add a physics material to your wheels for better grip control
  • Camera Following: Add a smooth follow camera for better gameplay feel
  • Common Issues and Solutions

  • Car flips too easily?
  • Lower the center of mass
  • Reduce turnSpeed
  • Increase angularDragAmount
  • Movement feels floaty?
  • Increase dragAmount
  • Adjust rigidbody mass
  • Turning too sharp/weak?
  • Adjust turnSpeed
  • Fine-tune angularDragAmount
  • Next Steps

    Once you have this basic controller working, you might want to add:
  • Wheel rotation animation
  • Particle effects for tire smoke
  • Engine sounds
  • Speedometer UI
  • More realistic suspension
  • Conclusion

    This simple car controller gives you a foundation to build upon. While it's basic, it provides realistic physics-based movement that you can expand based on your game's needs.
    Remember, game development is all about iteration - start simple and build up gradually. Happy coding! 🎮
    Feel free to leave comments if you have questions or need help troubleshooting your implementation!

    Comments