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

> 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.

- **Canonical page:** https://gamecrew.ai/techniques/unity/arcade-vehicle-city-rp-loop
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Unity 6
- **Category:** physics
- **Tags:** `vehicle`, `car`, `driving`, `drift`, `suspension`, `open-world`, `city`, `gta`, `rp`, `taxi`, `traffic`, `minimap`, `physics`
- **Verification:** Compile-verified pattern
- **Revision:** 1 (2026-11-30)
- **Demo:** 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 $\mathbf{w}_i$ by `restLength + wheelRadius`. On hit at distance $L$:
   $$\text{compression} = \max(0,\; L_{\text{rest}} - (L - r_{\text{wheel}})), \qquad F_n = k_s\,\text{compression} - k_d\,v_{\text{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 $\mathbf{v}_i = \text{rb.GetPointVelocity}(\mathbf{w}_i)$ onto the wheel's right axis $\hat{\mathbf{r}}_i$:
   $$F_{\text{lat}} = -v_{\text{lat}} \cdot \mu_{\text{grip}} \cdot m_{\text{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 $\delta(v) = \delta_{\max} \cdot \text{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`)

```csharp
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
