GameCrew AIEarly access
Sign in
Unity 6physicsRevision 1 · Compile-verified pattern

Arcade Raycast Vehicle Physics, Enter/Exit Driving & Modular City RP Loop in Unity 6

Updated

Responsive raycast 4-wheel spring-damper vehicle physics in Unity 6 with speed-curved steering, handbrake drifting, seamless on-foot enter/exit vehicle handoff, and instanced modular city blocks with cheap waypoint traffic for WebGL.

  • vehicle
  • car
  • driving
  • drift
  • suspension
  • open-world
  • city
  • gta
  • rp
  • taxi
  • traffic
  • minimap
  • physics

No demo.

When to Use (and When Not To)

Use raycast 4-wheel spring-damper vehicles for open-world city roleplay, taxi/delivery rush, urban heists, stunt sandboxes, and arcade racing games where responsive cornering, predictable drifting, curb tolerance, and instant enter/exit on-foot switching matter more than tire-compound simulation.

Avoid WheelCollider defaults in fast WebGL prototypes: WheelCollider frequently snags on modular road seams and flips unpredictably under WebGL frame-rate variance. Four deterministic raycasts in FixedUpdate are rock-solid, tunable in seconds, and trivial to test in PlayMode.

Mathematical & Algorithmic Core

  1. Per-Wheel Spring-Damper Suspension: Cast downward from each wheel hub w_i by restLength + wheelRadius. On hit at distance $L$: $compression = max(0,\; L_rest - (L - r_wheel)), F_n = k_s\,compression - k_d\,v_vertical$ Apply $\max(0, F_n)\,\hat{\mathbf{u}}_{\text{car}}$ at $\mathbf{w}_i$ via rb.AddForceAtPosition(...).
  2. Lateral Grip vs. Drift Slip Curve: Project wheel point velocity v_i = rb.GetPointVelocity(w_i) onto the wheel's right axis r_i: $F_lat = -v_lat · μ_grip · m_wheel$ Drop rear-wheel $\mu_{\text{grip}}$ smoothly from 0.88 to 0.34 while handbrake is held for controllable power-slides without spinouts.
  3. Speed-Sensitive Steering & Low Center of Mass: Clamp steer angle δ(v) = δ_max · lerp(1.0, 0.35, v / v_max) and lower rb.centerOfMass = new Vector3(0f, -0.45f, 0.1f) so hard turns lean excitingly without rolling onto the roof.
  4. Browser-Safe Open City Architecture: Build the city from 6–10 modular prefabs (straight road, T-junction, crossroad, sidewalk block, low-poly facade shells) sharing 2–3 atlased materials and GPU-instanced street props (DrawMeshInstanced). Drive ambient traffic along closed spline/waypoint rings using kinematic transforms (no Rigidbody per ambient car!) so 15–25 moving vehicles cost < 0.3 ms CPU.

Engine Implementation

Raycast 4-Wheel Arcade Car & On-Foot Enter/Exit (Assets/Game/Runtime/Vehicles/ArcadeCarController.cs)

using CCGD;
using UnityEngine;

namespace Game.Vehicles
{
    [RequireComponent(typeof(Rigidbody))]
    public sealed class ArcadeCarController : MonoBehaviour
    {
        [Header("Wheel Hubs (FL, FR, RL, RR)")]
        public Transform[] WheelHubs = new Transform[4];
        public Transform[] WheelVisuals = new Transform[4];
        public Transform SeatExitPoint;
        public LayerMask GroundMask = ~0;

        [Header("Suspension")]
        public float RestLength = 0.55f;
        public float WheelRadius = 0.34f;
        public float SpringStiffness = 28000f;
        public float DamperStrength = 3400f;

        [Header("Drive & Drift")]
        public float MotorForce = 11500f;
        public float ReverseForce = 6500f;
        public float MaxSpeedMps = 28f;
        public float MaxSteerDeg = 32f;
        public float HighSpeedSteerDeg = 12f;
        public float FrontGrip = 8.5f;
        public float RearGrip = 8.0f;
        public float DriftRearGrip = 2.6f;

        public bool Occupied { get; private set; }
        public float SpeedMps => rb != null ? Vector3.Dot(rb.linearVelocity, transform.forward) : 0f;

        Rigidbody rb;
        float throttleInput;
        float steerInput;
        bool handbrake;
        GameObject driverObject;

        void Awake()
        {
            rb = GetComponent<Rigidbody>();
            rb.mass = 1250f;
            rb.centerOfMass = new Vector3(0f, -0.45f, 0.12f);
            rb.linearDamping = 0.12f;
            rb.angularDamping = 0.8f;
        }

        public void EnterVehicle(GameObject player)
        {
            if (Occupied || player == null) return;
            driverObject = player;
            Occupied = true;
            player.SetActive(false);
        }

        public void ExitVehicle()
        {
            if (!Occupied || driverObject == null) return;
            Vector3 exitPos = SeatExitPoint != null
                ? SeatExitPoint.position
                : transform.position - transform.right * 2.1f + Vector3.up * 0.4f;
            driverObject.transform.position = exitPos;
            driverObject.SetActive(true);
            driverObject = null;
            Occupied = false;
            throttleInput = 0f;
            steerInput = 0f;
            handbrake = true;
        }

        void Update()
        {
            if (!Occupied) return;
            Vector2 move = GameInput.Move;
            steerInput = Mathf.Clamp(move.x, -1f, 1f);
            throttleInput = Mathf.Clamp(move.y, -1f, 1f);
            handbrake = GameInput.JumpHeld;

            if (GameInput.InteractPressed) ExitVehicle();
        }

        void FixedUpdate()
        {
            if (WheelHubs == null || WheelHubs.Length < 4) return;
            float speedRatio = Mathf.Clamp01(Mathf.Abs(SpeedMps) / Mathf.Max(1f, MaxSpeedMps));
            float steerDeg = Mathf.Lerp(MaxSteerDeg, HighSpeedSteerDeg, speedRatio) * steerInput;
            int groundedCount = 0;

            for (int i = 0; i < 4; i++)
            {
                Transform hub = WheelHubs[i];
                if (hub == null) continue;
                bool isFront = i < 2;
                Quaternion wheelRot = isFront
                    ? hub.rotation * Quaternion.Euler(0f, steerDeg, 0f)
                    : hub.rotation;
                Vector3 wheelFwd = wheelRot * Vector3.forward;
                Vector3 wheelRight = wheelRot * Vector3.right;

                float rayLen = RestLength + WheelRadius;
                if (Physics.Raycast(hub.position, -hub.up, out RaycastHit hit, rayLen, GroundMask, QueryTriggerInteraction.Ignore))
                {
                    groundedCount++;
                    float compression = Mathf.Max(0f, RestLength - (hit.distance - WheelRadius));
                    Vector3 pointVel = rb.GetPointVelocity(hub.position);
                    float upVel = Vector3.Dot(pointVel, hub.up);
                    float springForce = Mathf.Max(0f, compression * SpringStiffness - upVel * DamperStrength);
                    rb.AddForceAtPosition(hub.up * springForce, hub.position, ForceMode.Force);

                    // Lateral traction (drops on rear wheels during handbrake drift).
                    float latVel = Vector3.Dot(pointVel, wheelRight);
                    float grip = isFront ? FrontGrip : (handbrake ? DriftRearGrip : RearGrip);
                    float latForce = -latVel * grip * (rb.mass * 0.25f);
                    rb.AddForceAtPosition(wheelRight * latForce, hub.position, ForceMode.Force);

                    // Longitudinal drive / braking.
                    if (Occupied && !handbrake)
                    {
                        float fwdVel = Vector3.Dot(pointVel, wheelFwd);
                        if (throttleInput > 0.05f && fwdVel < MaxSpeedMps)
                            rb.AddForceAtPosition(wheelFwd * (throttleInput * MotorForce * 0.25f), hub.position, ForceMode.Force);
                        else if (throttleInput < -0.05f && fwdVel > -MaxSpeedMps * 0.45f)
                            rb.AddForceAtPosition(wheelFwd * (throttleInput * ReverseForce * 0.25f), hub.position, ForceMode.Force);
                    }
                    else if (!Occupied || handbrake)
                    {
                        float fwdVel = Vector3.Dot(pointVel, wheelFwd);
                        rb.AddForceAtPosition(wheelFwd * (-fwdVel * rb.mass * 0.55f), hub.position, ForceMode.Force);
                    }

                    UpdateWheelVisual(i, hit.distance - WheelRadius, steerDeg, isFront);
                }
                else
                {
                    UpdateWheelVisual(i, RestLength, steerDeg, isFront);
                }
            }

            // Gentle upright assist when airborne so jumps land cleanly.
            if (groundedCount == 0)
            {
                Vector3 uprightTorque = Vector3.Cross(transform.up, Vector3.up);
                rb.AddTorque(uprightTorque * 1200f, ForceMode.Force);
            }
        }

        void UpdateWheelVisual(int i, float suspensionDist, float steerDeg, bool isFront)
        {
            if (WheelVisuals == null || i >= WheelVisuals.Length || WheelVisuals[i] == null) return;
            WheelVisuals[i].localPosition = new Vector3(0f, -suspensionDist, 0f);
            if (isFront) WheelVisuals[i].localRotation = Quaternion.Euler(0f, steerDeg, 0f);
        }
    }
}

Performance & Platform Traps

  • Road Seam Snagging: Use a single continuous BoxCollider per straight block (or smooth terrain collider) rather than dense per-tile MeshCollider strips so raycast wheels never catch edges.
  • City Draw-Call Discipline: Keep visible city blocks under 180 draw calls and 250k triangles on WebGL by sharing one tiled road/sidewalk material, one modular building trim atlas, and GPU-instanced lampposts/trees/parked cars.
  • Unstuck & Flip Recovery: Include a respawn/upright button (R) or automatic flip recovery after 2.5 s inverted so players never get stuck upside-down in an alley.

Verification Checklist

  1. In PlayMode, accelerate forward for 2 seconds and assert SpeedMps > 8f with all 4 wheels grounded and zero roll-over.
  2. Test EnterVehicle and ExitVehicle toggling cleanly between on-foot camera/movement and car chase camera.
  3. Capture street-level and driving views and verify readable road markings, building silhouettes, and mission waypoint beacon.

Official references

  • Space Dust Racing Arcade Raycast Car Physics (GDC)
  • Marco Monster Car Physics for Games
  • Unity 6 FixedUpdate Rigidbody Force Architecture

More Unity 6 games

Games made with GameCrew on the same engine. No game has been built with this guide yet: these show what Unity 6 games here look like.

Fjordline — Leap from a granite wall under the midnight sun and carve one unbroken wingsuit line through Norway's most dramatic landscapes, from summit to sea, skimming close enough to touch the rock.

Fjordline

Leap from a granite wall under the midnight sun and carve one unbroken wingsuit line through Norway's most dramatic landscapes, from summit to sea, skimming close enough to touch the rock.

Saltwood Alley — Step up to the sunlit timber lanes of an old seaside arcade, feel the weight of turned maple in your palm, and bend real wrist-spin shots into tight vintage scoring cups.
Plays in VR

Saltwood Alley

Step up to the sunlit timber lanes of an old seaside arcade, feel the weight of turned maple in your palm, and bend real wrist-spin shots into tight vintage scoring cups.

More Unity 6 techniques

physics

CharacterController Slope Projection & Floor Snap in Unity 6 →

Deterministic Unity 6 CharacterController locomotion with SphereCast ground projection, ramp stickiness, steep-slope slide, and coyote jumps.

gameplay

Branching NPC Dialogue, Shot-Reverse-Shot Cutscenes, Cosmetics Shop & Safe-Area Mobile UI in Unity 6 →

Complete RPG/social loop in Unity 6: data-driven branching NPC dialogue trees, VR-safe shot-reverse-shot cutscene cameras, coin/cosmetics unlock shop with CCGD.CloudSave persistence, and phone safe-area layout via CCGD.GameUI.PageInsets.

gameplay

Solo-First Multiplayer Rooms, Named Hubs & VR Avatars with CCGD.GameNet in Unity 6 →

Browser-ready multiplayer in Unity 6 using CCGD.GameNet: solo-first host authority, 60 Hz interpolated avatars, named social rooms (JoinRoom/LeaveRoom), VR head-and-hand pose sync, cosmetic tags, and deterministic GameNet.Sim PlayMode tests.

gameplay

Frame-Rate-Independent Procedural Springs, Squash-Stretch & Trauma Feel in Unity 6 →

Exact dt-invariant second-order critically/under-damped spring dampers, Squirrel Eiserloh T^2 rotational Perlin camera trauma, volume-preserving squash-and-stretch, and TestClock-safe hit-stop.

Read via free MCP — or sign in to add techniques & beta test

Use /mcp/library free with no login to query guides, or connect via OAuth at /mcp to contribute technique guides and beta test cloud builds.

Connect via MCP