Three.js & Rapier Physics (Part 2):
How to Add Night Lighting to a
GTA-Style Car Game
By Shane Brumback · · Three.js tutorial
Premium Three.js night lighting tutorial, Part 2 of my GTA-style driving series: take the drivable muscle car from Part 1 into a night city with street lamps, fake volumetric light beams, lit skyscraper windows, headlights, brake lights and lens flares. 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 a Three.js Night Scene? (Quick Definition)
A Three.js night scene is lit mostly by things you fake, not by real lights. A dark sky, haze and a weak moon set the mood; volumetric beams are soft additive cones; street lamp pools, lit windows and headlight glows are emissive or additive shapes; and only a handful of real lights follow the car so the scene stays fast on phones.
Introduction
In Part 1 we loaded a 1971 muscle car, split its wheels and drove it with the Rapier vehicle controller. In this part we take the same car and the same physics into a night city: street lamps every 24 m with light beams and glowing ground pools, floodlit walls, a random pattern of lit skyscraper windows, and headlights, tail lights and lens flares on the car.
The trick is that almost none of it is a real light. Real point and spot lights are expensive in Three.js, especially on phones, so the scene fakes the look with additive cones, ground decals and shader tweaks, and moves a small pool of real lights from lamp to lamp only while you cannot see them switch.
What You'll Learn
- How to build fake volumetric light cones that fade along the beam and at their edges, all instanced in one draw call
- How to place street lamps along the sidewalk edge automatically and wash building walls with floodlights
- How to light skyscraper windows using only the building materials, with no extra textures
- How to move a small pool of real lights between lamps without anyone seeing a light switch on
- Headlights, brake lights that brighten when you brake, lens flares that draw in front of the car body, and a soft contact shadow
Prerequisites
- A recent browser and a text editor
- Comfortable with a basic Three.js scene and loading a GLB
- Best: Part 1: Load a GTA-Style Car and Drive It, which builds the car and the driving physics this part lights up
- 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 file is 20 steps: the Part 1 sunset drive expanded with night sky lighting, glowing street lamp beams and ground pools, lit skyscraper windows, headlights, and roadside palm trees.
- Street lamps stand about every 24 m along the sidewalk edge, each with an instanced volumetric beam and a ground pool.
- Only 12 real lights (6 on phones) follow the car around the city; the rest of the lighting is faked.
- The car is the same 1,150 kg rear-wheel-drive muscle car as Part 1, with the same suspension and drift numbers.
Fake Volumetric Light That Stays Fast
A real volumetric light needs ray marching through fog, which is too slow for a phone. Instead each beam is a cone with an additive shader: bright near the lamp, fading with distance and toward the cone edges, and softened where it meets the ground. Hundreds of beams draw in one instanced call, and a glow pool on the ground sells the light landing on the street.
Real Lights Only Where You Look
Three.js shades every real light on every lit surface, so a city with a hundred real lamps would crawl. The code keeps a small pool of real point lights and moves one to a new lamp only while both the old lamp and the new one are off screen or deep in the haze, aimed at the street ahead of the car. You see lit asphalt everywhere you drive and never see a light pop on.
Instanced Street Lamps & Pooled Lights (Preview)
Instead of creating a hundred expensive Three.js lights, Part 2 instances the volumetric cones and recycles a small pool of real THREE.PointLight instances ahead of the car:
// One InstancedMesh draws every additive street-lamp light cone in a single call
const beamMat = new THREE.ShaderMaterial({
transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
uniforms: { uColor: { value: new THREE.Color(0xffb86c) } },
vertexShader: beamVert, fragmentShader: beamFrag
});
const beams = new THREE.InstancedMesh(coneGeo, beamMat, lamps.length);
scene.add(beams);
// Recycle a small pool of real Three.js PointLights onto the nearest off-screen lamps
const lightPool = Array.from({ length: 6 }, () => {
const pl = new THREE.PointLight(0xffb566, 18, 26, 1.7);
scene.add(pl);
return { light: pl, lampIndex: -1 };
});
How It Works
- Imports, settings and renderer. Load three.js, OrbitControls, GLTFLoader, the meshopt decoder and Rapier, and set every driving number in one place.
- Night sky, moonlight and fog. Set the city at night with a black-blue sky, a few hundred stars, a weak blue moon for soft shadows, a low ambient fill and thick haze.
- Volumetric light beams and ground pools. Build fake volumetric light: soft additive cones that fade along the beam and at their edges, plus round glow pools on the ground, all instanced.
- 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.
- Street lamps and building floodlights. Stand a street lamp on the sidewalk edge about every 24 m with a volumetric beam and a ground pool, and wash street-facing walls with floodlights.
- Lit windows from the building materials. Light a random pattern of skyscraper windows using only the building materials: the shader finds glass by its low roughness and lights some cells.
- Real lights that follow the car. Move a small pool of real point lights between street lamps only while both lamps are off screen or deep in the haze, aimed at the street ahead, so you never see a light switch on.
- 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. A baked, posed driver sits inside with his hands on the wheel.
- Headlights, tail lights and lens flares. Give the headlights and brake lights glowing materials, add two spot lights with short volumetric beams, lens flares that draw in front of the car body, tail lights that brighten when you brake, and a soft contact shadow under the car.
- 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.
- 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: attract-mode 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 moon, the real street lights, the car lights and the 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. When the rain from Part 3 is on, wet roads get neither.
- 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). If the Part 3 rain is on, a rain loop fades in with it.
- 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
- Change the lamp spacing and the beam color in the street lamp step to restyle the whole city at once.
- Raise
REAL_LAMPSon desktop for more real lit asphalt, or lower it if a phone struggles. - Tune the haze color and density in the night sky step: thicker haze hides the map edge and makes the beams read better.
- Everything from Part 1 still applies:
ENGINE_FORCE,REAR_GRIP,SUSP_STIFFandDRIFT_GRIPtune how the car drives.
Frequently Asked Questions
How do I make a night scene in Three.js?
Use a near-black sky, dense fog or haze, a weak bluish directional light for the moon and a low hemisphere fill. Then add light the cheap way: emissive windows and lamp heads, additive cones for beams, additive ground decals for light pools, and only a few real lights near the camera.
How do I fake volumetric light beams in Three.js?
Draw each beam as a cone with an additive, depth-write-off shader that fades along the beam and toward its edges, and soften it where it meets the ground. Use an InstancedMesh so every beam in the city is one draw call.
Why not use a real light for every street lamp?
Three.js shades every real light on every lit material, so the cost grows with the number of lights. A city with a hundred lamps would be far too slow on phones. This tutorial moves a small pool of real lights between lamps while they are out of view.
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.
Is the rain part of this tutorial?
No. This part's steps, downloadable code and Live Demo are the clear night scene; the rain is Part 3.
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.