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

> Crisp 4-wheel raycast spring-damper vehicle physics on RigidBody3D in Godot 4 with controllable drifting, seamless CharacterBody3D enter/exit driving handoff, and MultiMeshInstance3D modular city/traffic loops that hold 60 fps in WebGL.

- **Canonical page:** https://gamecrew.ai/techniques/godot/arcade-vehicle-city-rp-loop
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Godot 4
- **Category:** physics
- **Tags:** `vehicle`, `car`, `driving`, `drift`, `suspension`, `open-world`, `city`, `gta`, `rp`, `traffic`, `physics`
- **Verification:** Compile-verified pattern
- **Revision:** 1 (2026-11-30)
- **Demo:** No demo

## When to Use (and When Not To)

Use raycast 4-wheel suspension on `RigidBody3D` for open-world city roleplay, delivery/taxi missions, urban driving sandboxes, and arcade racers in Godot 4 where crisp steering, predictable drifting, curb tolerance, and instant on-foot enter/exit switching are essential.

Avoid complex tire-slip solvers in browser-targeted open cities: four `RayCast3D` probes in `_physics_process` stay stable across varying web frame rates and never bounce erratically over modular road seams.

## Mathematical & Algorithmic Core

1. **Spring-Damper Suspension Force**: For each wheel ray of length $L_{\text{rest}} + r_{\text{wheel}}$, measure compression $c = \max(0, L_{\text{rest}} - (d_{\text{hit}} - r_{\text{wheel}}))$ and vertical hub speed $v_u = \mathbf{v}_{\text{point}} \cdot \hat{\mathbf{u}}$:
   $$F_n = \max(0,\; k_s c - k_d v_u)$$
   Apply $F_n \hat{\mathbf{u}}$ at offset $\mathbf{w}_i - \mathbf{x}_{\text{body}}$ via `apply_force(force, offset)`.
2. **Lateral Grip & Handbrake Drift**: Project point velocity onto the steered wheel right axis $\hat{\mathbf{r}}_i$ and oppose sideways slip with $F_{\text{lat}} = -v_{\text{lat}} \cdot \mu \cdot \frac{m}{4}$. Lowering rear $\mu$ while handbraking creates controllable drifts.
3. **Instanced Modular City Budget**: Place repeated streetlamps, trees, benches, and parked shells in `MultiMeshInstance3D` nodes and move ambient traffic along `Path3D` / waypoint arrays kinematically so a lively city stays under 120 draw calls in the WebGL Compatibility renderer.

## Engine Implementation

### Raycast Arcade Car & On-Foot Toggle (`Assets/Game/vehicles/arcade_car.gd`)

```gdscript
class_name ArcadeCar
extends RigidBody3D

@export var wheel_hubs: Array[Node3D] = [] # [FL, FR, RL, RR]
@export var exit_marker_path: NodePath
@export var rest_length: float = 0.55
@export var wheel_radius: float = 0.34
@export var spring_stiffness: float = 26000.0
@export var damper_strength: float = 3200.0
@export var motor_force: float = 11000.0
@export var max_speed_mps: float = 26.0
@export var max_steer_deg: float = 30.0
@export var high_speed_steer_deg: float = 11.0
@export var front_grip: float = 8.5
@export var rear_grip: float = 8.0
@export var drift_rear_grip: float = 2.6

var occupied: bool = false
var _driver: Node3D = null
var _throttle: float = 0.0
var _steer: float = 0.0
var _handbrake: bool = false

func _ready() -> void:
	mass = 1200.0
	center_of_mass_mode = RigidBody3D.CENTER_OF_MASS_MODE_CUSTOM
	center_of_mass = Vector3(0.0, -0.45, 0.12)
	linear_damp = 0.15
	angular_damp = 0.75

func enter_vehicle(driver: Node3D) -> void:
	if occupied or driver == null:
		return
	_driver = driver
	occupied = true
	driver.visible = false
	driver.set_physics_process(false)

func exit_vehicle() -> void:
	if not occupied or _driver == null:
		return
	var marker := get_node_or_null(exit_marker_path) as Node3D
	_driver.global_position = marker.global_position if marker != null else global_position - global_basis.x * 2.2 + Vector3.UP * 0.4
	_driver.visible = true
	_driver.set_physics_process(true)
	_driver = null
	occupied = false
	_throttle = 0.0
	_steer = 0.0
	_handbrake = true

func set_inputs(throttle: float, steer: float, handbrake: bool) -> void:
	_throttle = clampf(throttle, -1.0, 1.0)
	_steer = clampf(steer, -1.0, 1.0)
	_handbrake = handbrake

func forward_speed() -> float:
	return linear_velocity.dot(-global_basis.z)

func _physics_process(_delta: float) -> void:
	if wheel_hubs.size() < 4:
		return
	var space := get_world_3d().direct_space_state
	var speed_ratio := clampf(absf(forward_speed()) / maxf(1.0, max_speed_mps), 0.0, 1.0)
	var steer_rad := deg_to_rad(lerpf(max_steer_deg, high_speed_steer_deg, speed_ratio) * -_steer)
	var up := global_basis.y
	var ray_len := rest_length + wheel_radius

	for i in range(4):
		var hub := wheel_hubs[i]
		if hub == null:
			continue
		var origin := hub.global_position
		var query := PhysicsRayQueryParameters3D.create(origin, origin - up * ray_len)
		query.exclude = [get_rid()]
		var hit := space.intersect_ray(query)
		if hit.is_empty():
			continue

		var hit_dist := origin.distance_to(hit["position"] as Vector3)
		var compression := maxf(0.0, rest_length - (hit_dist - wheel_radius))
		var offset := origin - global_position
		var pt_vel := linear_velocity + angular_velocity.cross(offset)

		# 1. Suspension spring + damper.
		var up_vel := pt_vel.dot(up)
		var spring_f := maxf(0.0, compression * spring_stiffness - up_vel * damper_strength)
		apply_force(up * spring_f, offset)

		# 2. Steered wheel basis (-Z forward in Godot 3D).
		var is_front := i < 2
		var wheel_basis := hub.global_basis.rotated(up, steer_rad) if is_front else hub.global_basis
		var fwd := -wheel_basis.z
		var right := wheel_basis.x

		# 3. Lateral traction / drift slip.
		var lat_vel := pt_vel.dot(right)
		var grip := front_grip if is_front else (drift_rear_grip if _handbrake else rear_grip)
		apply_force(right * (-lat_vel * grip * mass * 0.25), offset)

		# 4. Longitudinal drive or parking brake.
		var fwd_vel := pt_vel.dot(fwd)
		if occupied and not _handbrake:
			if _throttle > 0.05 and fwd_vel < max_speed_mps:
				apply_force(fwd * (_throttle * motor_force * 0.25), offset)
			elif _throttle < -0.05 and fwd_vel > -max_speed_mps * 0.45:
				apply_force(fwd * (_throttle * motor_force * 0.16), offset)
		else:
			apply_force(fwd * (-fwd_vel * mass * 0.5), offset)
```

## Performance & Platform Traps

- **Road Collider Smoothness**: Merge straight road strips into box shapes rather than dense triangle meshes so raycasts stay fast and snag-free.
- **Compatibility Renderer Lighting**: Stick to one directional sun shadow plus baked/unlit street emissives; avoid dozens of shadow-casting `OmniLight3D` streetlamps in WebGL.
- **Syncing Vehicles Over `GameNet`**: In multiplayer RP hubs, only the driver's client simulates the car and publishes vehicle pose via `GameNet.send_event("veh_pose", ...)` or host state so remote players see smooth driving without physics fighting.

## Verification Checklist

1. In PlayMode, call `enter_vehicle`, apply `set_inputs(1.0, 0.0, false)` for 90 physics ticks, and assert `forward_speed() > 8.0`.
2. Call `exit_vehicle()` and verify the player `CharacterBody3D` reappears cleanly outside the door without clipping inside the chassis.
3. Verify modular street props use `MultiMeshInstance3D` so city vistas hold smooth browser frame rates.

## Official references

- Space Dust Racing Raycast Vehicle Architecture (GDC)
- Godot 4 RigidBody3D Physics Direct State & MultiMeshInstance3D Docs
