Lesson 116 +10 XP

Wheel Collider and Vehicle Physics

Wheel Collider and Vehicle Physics

The Wheel Collider is a specialized collider for ground vehicles. It simulates suspension, motor torque, and tire slip friction.

Setup Structure

To build a vehicle:

  1. Create a parent GameObject with a Rigidbody and assign a high mass (e.g. 1500 kg).
  2. Add child GameObjects for the wheels.
  3. Attach a Wheel Collider component to each wheel child.
  4. Keep the visual wheel meshes separate so they can rotate without affecting the collider physics.

Applying Inputs in Script

Control the vehicle by modifying the properties of the Wheel Colliders in FixedUpdate():

using UnityEngine;

public class CarDriver : MonoBehaviour
{
    public WheelCollider frontLeftWheel;
    public WheelCollider frontRightWheel;
    public Transform flMesh;
    public Transform frMesh;

    public float motorTorqueMax = 1000f;
    public float maxSteeringAngle = 35f;

    void FixedUpdate()
    {
        float accel = Input.GetAxis("Vertical");
        float steer = Input.GetAxis("Horizontal");

        // 1. Apply motor torque to drive wheels
        frontLeftWheel.motorTorque = accel * motorTorqueMax;
        frontRightWheel.motorTorque = accel * motorTorqueMax;

        // 2. Apply steer angle to steering wheels
        frontLeftWheel.steerAngle = steer * maxSteeringAngle;
        frontRightWheel.steerAngle = steer * maxSteeringAngle;

        // 3. Update mesh visuals
        UpdateVisualPose(frontLeftWheel, flMesh);
        UpdateVisualPose(frontRightWheel, frMesh);
    }

    void UpdateVisualPose(WheelCollider col, Transform mesh)
    {
        col.GetWorldPose(out Vector3 pos, out Quaternion rot);
        mesh.SetPositionAndRotation(pos, rot);
    }
}

Key Properties

  • motorTorque: Rotational force applied to the wheel.
  • brakeTorque: Braking force applied to slow down the wheel.
  • steerAngle: Steer angle in degrees.
  • GetWorldPose(): Returns the calculated physical position (including suspension travel) and rotation of the wheel.

TL;DR

  • Wheel Colliders require a parent Rigidbody to calculate mass and forces.
  • Set motorTorque, brakeTorque, and steerAngle inside FixedUpdate().
  • Use GetWorldPose() to align visual wheel meshes with the physical collider.