Three.js & Rapier Physics (Part 1):
How to Create a
GTA-Style Car Game
By Shane Brumback · · Three.js tutorial
Premium three js vehicle physics tutorial: build a GTA style car with the Rapier vehicle controller, suspension, wheel friction and drifting in a small downtown city. Live demo.
LIVE DEMO
The muscle car behind this page is the finished file running live. Launch the full-screen demo to drive it through the downtown streets, drift it with the handbrake and knock the barrels and cones around.
Free: sign in free with Google. W/S or up/down arrows give gas and brake, A/D or the left/right arrows steer, Space drifts, R flips the car back, drag or one finger orbits; on phones turn to landscape and use the twin-stick controls. Esc exits.
What Is Three.js Vehicle Physics? (Quick Definition)
Three js vehicle physics means letting a physics engine move your car while Three.js draws it. With Rapier's vehicle controller, the chassis is one dynamic rigid body and each wheel is a raycast with a spring, damping and tyre friction. You set engine force, brakes and steering per wheel, step the world, and copy the chassis pose and wheel positions into your meshes.
Introduction
In this Sunset Drive tutorial we build a GTA-style car with Rapier vehicle physics that you can actually drive: a 1971 muscle car with real weight, soft suspension that leans and dives, rear-wheel drive and a handbrake drift, in a small downtown with buildings, sidewalks, barrels, cones and jersey barriers. If you want the why before the how, read the free article Three.js Car Physics: Why GTA-Style Driving Feels So Good first. It is the same car and the same numbers.
It is also a practical lesson in using real downloaded models in a threejs car game: splitting wheels that came joined, placing a building pack on city blocks, and turning a road mesh and a scanned ground grid into physics you can drive anywhere on, generated by code instead of by hand.
What You'll Learn
- How the Rapier vehicle controller works: raycast wheels, suspension rest length, stiffness, damping and friction slip
- How to give a car weight: mass, a low ballast collider and springs placed so the wheels land where the model drew them
- Rear-wheel drive, braking into reverse, speed-sensitive steering and a handbrake drift
- How to split one four-wheel mesh into four wheels that steer and roll
- How to scan a road mesh with rays to build drivable ground, building colliders and street props automatically
- A chase camera with drag and touch orbit, plus the site-wide twin-stick controls for phones
Prerequisites
- A recent browser and a text editor
- Comfortable with a basic Three.js scene (camera, renderer, a mesh) and loading a GLB
- Helpful: my Rapier physics rocket lander tutorial for rigid bodies and a fixed timestep
- The free article Three.js Car Physics: Why GTA-Style Driving Feels So Good
Facts
- Libraries: three.js r160 and @dimforge/rapier3d-compat 0.14.0, both from a CDN. No build step.
- The car weighs about 1,150 kg, is rear-wheel drive with 3,000 N per rear wheel, and reaches about 82 km/h after 5 seconds on flat ground.
- Suspension: 0.3 m rest length, stiffness 30 per kg, about 8 cm of sag at rest, 0.25 m of travel.
- Grip: front 2.6, rear 3.2, rear 1.3 with the handbrake on. Steering lock goes from 0.6 to 0.18 radians as speed rises.
- The map is scanned with a ray every 2 m (about 78,000 rays) and the ground grid becomes one trimesh collider, so you can drive off the road anywhere.
- The three models download as about 7.4 MB of meshopt-compressed GLB.
Rapier Vehicle Controller vs Wheel Bodies
You can build a car from four cylinder bodies and joints, but they catch on the triangle edges of a road mesh and wobble at speed. The rapier vehicle controller is a raycast vehicle: each wheel is a ray with a spring and a tyre model. It is cheaper, steadier on bumpy city geometry and much easier to tune, which is why most arcade and GTA-like driving uses this approach.
Three.js Car Physics That Feels Heavy
Weight is mostly suspension. Rapier multiplies spring force by the chassis mass, so a stiffness of 30 with four wheels sags 9.81 / (4 x 30), about 8 cm. The code uses that number to hang each spring so the wheels sit exactly where the model drew them, then damps the springs a little under critical so the car dives, squats and rolls and then settles.
Core Three.js & Rapier Setup (Preview)
A quick look at how the sunset drive tutorial wires the Rapier raycast vehicle controller to a Three.js chassis and four independent wheels:
// Create a dynamic chassis body and attach Rapier's raycast vehicle controller
const chassis = world.createRigidBody(
RAPIER.RigidBodyDesc.dynamic().setTranslation(0, 1.2, 0).setLinearDamping(0.15)
);
const vehicle = world.createVehicleController(chassis);
const wheelDir = { x: 0, y: -1, z: 0 }, axle = { x: -1, y: 0, z: 0 };
for (const pos of [[-0.82, 0.35, 1.38], [0.82, 0.35, 1.38], [-0.82, 0.35, -1.32], [0.82, 0.35, -1.32]]) {
vehicle.addWheel({ x: pos[0], y: pos[1], z: pos[2] }, wheelDir, axle, 0.30, 0.36);
}
// Each frame: apply rear-wheel engine force, front steering, and step suspension
vehicle.setWheelEngineForce(2, throttle * 3000);
vehicle.setWheelEngineForce(3, throttle * 3000);
vehicle.setWheelSteering(0, steerAngle);
vehicle.setWheelSteering(1, steerAngle);
vehicle.updateVehicle(dt);
How It Works
- Imports, settings and renderer. Load three.js, OrbitControls, GLTFLoader, Sky, the meshopt decoder and Rapier, and set every driving number in one place.
- Sunset sky, sun, fog and a mountain horizon. Add the Sky shader, a fixed warm sun with crisp, steady shadows, a hemisphere fill light, warm fog and a ring of hazy mountain ranges.
- Physics world, the roads and the downtown buildings. Start Rapier, load the four GLB models (roads, buildings, car and driver), turn the road meshes into one trimesh collider and move each building onto a city block.
- Scan the streets: ground fill and a drivable ground. Cast a ray down every 2 m to map the roads, flood-fill ground heights, and turn the whole ground grid into one trimesh collider with a solid box for each building, so the car can drive anywhere.
- Street props: barrels, cones, jersey barriers and rubble. Scatter knockable barrels and cones, fixed jersey barriers and decorative rubble along the sidewalk edges and across road exits.
- The car: model, four separate wheels, and the chassis body. Split the single four-wheel mesh into four wheel meshes, put each in a steering pivot, and give the car a dynamic body with a low ballast collider and a soft blob shadow. A baked, posed driver sits inside with his hands on the wheel.
- Raycast vehicle: suspension, tyre grip and steering. Create the Rapier vehicle controller and add four wheels with spring, damping, travel and friction settings.
- Driving input: keyboard and the mobile twin-stick. Map W/S and up/down to gas and brake, A/D or left/right arrows to steering, Space and R, and wire the site-wide twin-stick controls for phones.
- Engine, brakes, steering and the handbrake drift. Each physics step, turn the input into engine force, brakes, speed-sensitive steering and the handbrake drift settings for every wheel. The brake lights flare red whenever you brake, and the two white reverse lights come on while you back up, bright enough to see in daylight.
- HUD: speedometer and drift meter. Show km/h, mph, drive or reverse, and a drift readout based on how fast the car is moving sideways.
- Camera: auto-orbit behind the page, chase cam and drag orbit in the demo. Slowly orbit the parked car behind the page text, then in the demo follow the car and ease back behind it after you drag to orbit.
- Main loop, resize and Live Demo hooks. Step the physics at a fixed 60 Hz, copy the chassis, wheels and props into their meshes, move the sun and camera, and expose enter and exit for the Live Demo button.
- A driver, tire marks and dust. Seat a posed driver with his hands on the wheel, then lay fading rubber marks and kick up dust whenever the rear tires spin as you take off (forward or in reverse), you brake hard, the car slides sideways through a turn, or you pull the handbrake.
- Sound: engine, tire screech, crashes, the horn and the rain. Add real engine, tire screech, crash and horn recordings with the Web Audio API: the engine revs through the gears as you speed up and drops off when you let go of the gas, the tires squeal when they slip or you brake hard, a crash plays when the car hits something, and H holds the horn (M mutes).
- Street lamps along the sidewalks. Place instanced street lamp poles, overhang arms and fixture heads along the sidewalk curb about every 24 m, facing the road and clear of building footprints. In Part 1 they stand as unlit sunset fixtures; Part 2 lights them up at night and Part 3 adds collision and knock-over physics.
- Palm trees and roadside landscaping. Line the sidewalks with instanced palm trees in raised stone planters (curved ringed trunks, coconuts and 10 arched feathered fronds), paired with clustered tropical shrubs, accent blooms, trimmed hedge strips and thin trunk colliders.
The detailed code breakdown and the full copy-paste file are below. Members unlock them. Every step is an exact excerpt of the full file, and the full file is the same code as the live demo.
How To Use It
- Start with
ENGINE_FORCE,FRONT_GRIPandREAR_GRIP. Drop the rear grip below the front and the car starts to oversteer under power; raise it and the car pushes wide. - Change
SUSP_STIFFto 15 for a floaty old sedan or 60 for a stiff sports car. The wheels stay in place because the spring position is worked out fromSUSP_SAG. - Make the drift easier or harder with
DRIFT_GRIPandDRIFT_SIDE. - To use your own car, point its nose down +X, make sure the wheel mesh name contains "Wheel", and the split code finds the four corners for you.
Frequently Asked Questions
How do I add vehicle physics in Three.js?
Use Three.js to draw the car and a physics engine to move it. With Rapier you create a dynamic rigid body for the chassis, call world.createVehicleController(chassis), add four raycast wheels with suspension and friction settings, and every frame set engine force, brakes and steering, call updateVehicle and copy the results into your meshes.
Is the full source free?
No. This is a premium Level 3 tutorial. The live demo is free: sign in free with Google to launch it. Members unlock the step-by-step code, the full file and the Launch button.
Can I use the Rapier vehicle controller with my own car model?
Yes. Point the car's nose down +X (or change the forward axis), measure each wheel's centre and radius, and split the wheels into their own meshes if the model joins them. The tutorial does that split in code by sorting each triangle into a corner.
Why does the car drift when I hold Space?
Space is the handbrake. It brakes the rear wheels and lowers their grip and sideways stiffness, so the rear slides out. Steer into the slide and let go to get the grip back.
Does the demo work on phones?
Yes. Turn your phone to landscape: the left stick is only gas and brake, the right stick steers the wheels, DRIFT and FLIP buttons sit on the right, and the camera stays behind the car. The city models are about 7 MB, so the first load takes a few seconds on mobile data.
Related Tutorials and Articles
- Three.js Rapier Physics Tutorial: Build a Rocket Lander: rigid bodies, forces and a fixed timestep with the same Rapier version.
- Drift Dash: Free Three.js 3D Drift Racing Game: my one-touch arcade drift racer.
- Three.js Rapier Physics: Landing a 3D Rocket with Real Rigid Bodies: the free article on Rapier basics.
READ THE FREE ARTICLE
Want the why before the how? Read Three.js Car Physics: Why GTA-Style Driving Feels So Good, then go drift in Drift Dash.
3D Model Credits
- Car: Phoenix 455 '71 by DanielZhabotinsky, licensed CC BY 4.0. I optimized it and split the wheels in code.
- Buildings: Downtown Buildings Set by DanielZhabotinsky, licensed CC BY 4.0. I optimized it and moved each building onto a city block.
- Roads: [FREE] City Road Layout Mockup by 99.Miles, licensed CC BY 4.0. I optimized it for the web.
- Driver: Gangster Rigged by PropShop™, licensed CC BY 4.0. I rigged him with a humanoid skeleton, posed him in the driver's seat, and optimized the model for the web.
- Sounds (all CC0): an engine hum made in code for this demo, Screeching Tires #1 by Dorian Clair, Car horn #4 by Denis Chardonnet, Crash Collision by qubodup, and AMB Rain Loop 1 from OpenGameArt. I trimmed them into short loops.
- GTA is only used here as a style comparison. This demo has no Rockstar art, logos or code.