webdevpuneet.com

Matter.js Hill Climb Car Game — Boost, Coins and Flips

Matter.js Hill Climb Car Game · Games · Plain HTML, CSS & JS · Live preview

CategoryGames

About this UI Snippet

Matter.js Hill Climb Car — Suspension, Boost, Coins, Flip Tricks and a Parallax World

Screenshot of the Matter.js Hill Climb Car Game snippet rendered live

Hill Climb Racing's charm is pure physics: a floppy little car, bumpy hills and a driver whose head must never touch the ground. This snippet rebuilds that loop with Matter.js and turns it into a complete game with a start screen, a 500 m summit to reach, coins, a nitro boost, flip bonuses, dust and flame particles, screen shake, a parallax landscape and optional engine sound. Everything is plain JavaScript on one canvas.

The car: three bodies and some springs

The chassis is a chamfered rectangle; each wheel is a circle joined to it by two constraints, a soft short spring from above (the suspension) and a diagonal one that stops the wheel sliding along the body. A small head body sits on a stiff neck. All parts share a negative collision group from Body.nextGroup(true), so wheels never collide with their own chassis. The car is drawn by hand each frame from the bodies' positions and angles.

Driving by spinning wheels, and boost

The engine never pushes the car. While a pedal is held, the wheels' angular velocity is eased toward a maximum with Body.setAngularVelocity, and wheel friction turns that spin into motion. Boost raises the target spin by 70% and adds a forward force along the chassis. It drains its own meter in about three seconds and refills slowly; collecting a coin gives a little back. Flame particles stream from the exhaust while it burns.

Air control and flip bonuses

When neither wheel touches the terrain (Query.collides), the pedals tilt the chassis instead of driving. While airborne, the game adds up the chassis rotation each step; if you land upright after turning roughly a full revolution, you earn 100 points per flip with a "Front flip" or "Back flip" popup. Landing upside down just counts as a crash.

Coins, fuel and the finish

Coin arcs follow the hills, and the middle of each arc floats high enough to reward a jump. Coins are plain objects checked by distance, so there are no extra physics bodies; the fuel cans are static sensors. Fuel drains while a pedal is held, a can refills it, and the run ends when your head hits the ground, you are upside down for 1.5 seconds, you stop with an empty tank, or you pass 500 m and reach the checkered flag. The score is distance plus 10 per coin plus flip bonuses, and your best is saved in localStorage.

Terrain without poly-decomp

Hills are summed sine waves whose amplitude grows with distance. Instead of one huge concave body, the ground is 520 thin static rectangles, each rotated to the slope between two sample points. The visible ground is drawn separately as a filled path with a dark lip and a grass stroke.

Camera, parallax and feel

With hasBounds: true, the renderer only draws what is inside render.bounds. Each frame the bounds ease toward the car, leading slightly in the direction of travel, and crashes add a decaying shake. The sun, clouds and two hill layers are painted last with destination-over at different scroll speeds, so they sit behind the world and give depth.

Sound and controls

Sound is off until you press the button, which is also what lets browsers start audio. An oscillator through a low-pass filter follows the car's speed and throttle, and short beeps mark coins, fuel, flips and crashes. Keyboard, on-screen touch pedals and a restart key are all supported.

What's included

Features

Sprung suspension
Two constraints per wheel give a soft spring and a diagonal locator.
Nitro boost with a meter
Boost raises wheel spin and adds a forward force, drains in about 3 seconds and recharges slowly.
Flip bonuses
Rotation is summed while airborne and rewarded on an upright landing with floating popups.
Coins and fuel cans
Distance-checked coin arcs follow the hills, and sensor fuel cans refill the tank.
500 m summit
A progress bar, distance markers every 50 m and a checkered flag give the run a goal.
Particles and shake
Dust, exhaust flames, sparkles, crash debris and a decaying screen shake add feel.
Parallax world
Sun, clouds and two hill layers scroll at different speeds behind the ground.
Sound, touch and saved best
Optional engine audio, three pointer-captured pedals and a best score kept in localStorage.

Step by step

How to Use

  1. 1
    Press Start drivingThe start card lists the goal: reach the 500 m summit. Press the button, Enter or → to begin.
  2. 2
    Gas, brake and boostHold → or D for gas, ← or A to brake and reverse, and ↑, W or Space for nitro. On a phone use the three on-screen pedals.
  3. 3
    Lean in the airWith both wheels off the ground the pedals tilt the car. Rotate a full turn and land upright for +100 flip points.
  4. 4
    Collect coins and fuelCoins add 10 points each and a little boost. Yellow cans refill the tank, so plan your throttle between them.
  5. 5
    Watch the progress barThe bar along the top of the stage shows how far you are from the checkered flag at 500 m.
  6. 6
    Beat your bestPress R to restart at any time. Your best score is remembered, and the Sound button adds engine noise and effects.

Real-world uses

Common Use Cases

Weekend game-jam starter
Reskin the car, hills and pickups to ship a full driving game quickly. The start screen, fuel, coins, boost and game-over flow are already wired together.
Vehicle physics lesson
Teach suspension, traction and torque with a car students can poke at. Changing a constraint's stiffness, the wheel friction or the boost force shows its effect immediately.
Game-feel reference
Study how particles, screen shake, a leading camera, floating text and sound turn a physics demo into something satisfying to play.
Procedural terrain experiments
Swap the summed-sine height function for craters, deserts or an endless climb, and see how the rotated-segment ground handles any curve.
Playable portfolio demo
Show interactive physics skill with a game people can actually drive, then walk through the constraints, flip detection and camera code in an interview.

Got questions?

Frequently Asked Questions

Make a chassis body and two circle wheels, connect each wheel with Constraints (a soft spring for suspension plus one to hold its position) and put all parts in one negative collision group. Drive by easing the wheels' angular velocity toward a target.

While both wheels are off the terrain, the game adds the change in chassis angle each step into airSpin. When a wheel touches down, if the car is upright and the total passed about 5.4 radians (almost a full turn), it awards 100 points per revolution and shows a popup. The sign of airSpin decides between front and back flip.

While the boost key is held and the meter has charge, the target wheel spin is multiplied by 1.7 and Body.applyForce pushes the chassis along its heading. The meter drains a little each step and recharges when you release, so it works as a short burst you spend on hills.

Create the renderer with hasBounds: true and update render.bounds.min and max every frame in beforeRender to centre on the body. Easing toward the target keeps it smooth, and adding a little velocity-based lead shows more of what is ahead.

Browsers only allow audio to start after a user gesture, so the Sound button creates the AudioContext when pressed. An oscillator through a low-pass filter plays the engine, and its pitch follows speed and throttle.

Copy & paste

Source Code

Requires
<div class="hc">
  <div class="hc-hud">
    <div><span>Distance</span><b id="hcDist">0 m</b></div>
    <div><span>Coins</span><b id="hcCoins">0</b></div>
    <div><span>Score</span><b id="hcScore">0</b></div>
    <div><span>Best</span><b id="hcBest">0</b></div>
    <div class="hc-meter"><span>Fuel</span><i><em id="hcFuel"></em></i></div>
    <div class="hc-meter boost"><span>Boost</span><i><em id="hcBoost"></em></i></div>
    <div class="hc-btns">
      <button type="button" id="hcSound" aria-pressed="false">Sound off</button>
      <button type="button" id="hcReset">Restart</button>
    </div>
  </div>
  <div class="hc-stage" id="hcStage">
    <div class="hc-prog" aria-hidden="true"><i id="hcProg"></i></div>
    <div class="hc-over" id="hcOver">
      <strong id="hcOverTitle">Hill Climb</strong>
      <span id="hcOverText">Reach the 500 m summit. Collect coins and fuel, pull off flips, and keep your head off the ground.</span>
      <div class="hc-stats" id="hcStats" hidden></div>
      <button type="button" id="hcAgain">Start driving</button>
    </div>
    <div class="hc-pedals">
      <button type="button" class="hc-pedal" id="hcBrake" aria-label="Brake / reverse">&#9664; Brake</button>
      <button type="button" class="hc-pedal boost" id="hcBoostBtn" aria-label="Boost"><svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M13 2 4 14h6l-1 8 9-12h-6z"/></svg> Boost</button>
      <button type="button" class="hc-pedal gas" id="hcGas" aria-label="Accelerate">Gas &#9654;</button>
    </div>
  </div>
  <p class="hc-hint"><kbd>&rarr;</kbd>/<kbd>D</kbd> gas &middot; <kbd>&larr;</kbd>/<kbd>A</kbd> brake &middot; <kbd>&uarr;</kbd>/<kbd>Space</kbd> boost &middot; <kbd>R</kbd> restart. Rotate in the air for flip bonuses.</p>
</div>

Extend with AI

Take This Snippet Further With AI

Paste this snippet into an AI assistant like Claude and ask it to explain how the two constraints per wheel make the suspension, or how airSpin and landed() turn rotation into flip bonuses. Since boost, coins, fuel, a finish line, particles, shake, parallax and sound already exist, ask for what is missing: an upgrade shop that spends coins on engine, tyres and fuel tank, new vehicles such as a bike or a monster truck, terrain generated in chunks so it never ends, a ghost of your best run, a combo multiplier for chained flips, or a day-to-night cycle with headlights. It can also help retune the handling for steeper maps.

Prompt to recreate it

Copy this into your AI assistant of choice to build the effect from scratch, or as a jumping-off point for your own variant:

text
Build a Hill Climb Racing-style game with Matter.js 0.20 (from a CDN) in plain HTML, CSS and JavaScript.

Requirements:
- Terrain: a height function of summed sine waves that steepens with distance, built from thin static rectangles rotated to each segment's slope, drawn as a filled brown path with a darker lip and a green grass edge. A 500 m finish with a checkered flag, distance markers every 50 m and a progress bar.
- Car: a rounded chassis, two high-friction circle wheels each joined by a soft suspension spring and a diagonal locating constraint, and a head body on a stiff neck, all in one negative collision group. Draw the car, wheels and driver by hand from the bodies each frame.
- Driving by easing the wheels' angular velocity toward a target (gas, brake/reverse). Nitro boost on Up/W/Space: multiply the target by 1.7 and apply a forward force along the chassis, with its own meter that drains in about 3 seconds and recharges slowly. When both wheels are airborne (Query.collides), gas and brake tilt the chassis instead.
- Flip tracking: sum the chassis rotation while airborne and, on an upright landing after nearly a full turn, award 100 points per revolution with a floating "Front flip"/"Back flip" popup.
- Pickups: coin arcs that follow the hills (checked by distance, no bodies; each gives 10 points and a bit of boost) and static sensor fuel cans that refill the tank. Fuel drains while driving.
- Effects: dust from driven wheels, exhaust flames while boosting, sparkles on pickups, crash debris and a decaying screen shake. A follow camera using hasBounds and render.bounds that leads slightly ahead, with a parallax sun, clouds and two hill layers painted with destination-over.
- Game flow: a start card, game over when the head hits the ground, the car is upside down for 1.5 s or it stops with no fuel, and a win at 500 m. A results card shows distance, coins and score; the best score is saved in localStorage with try/catch.
- HUD for distance, coins, score, best, fuel and boost. Keyboard (arrows/A/D, Up/W/Space, R) and three on-screen touch pedals using pointer capture.
- An optional sound toggle (off by default): an oscillator through a low-pass filter for the engine, with pitch following speed and throttle, plus short beeps for coins, fuel, flips and crashes.

Want to tighten it up first? Run this prompt through the AI Prompt Studio to score it across 8 quality dimensions, catch anti-patterns, and tune the wording for Claude, ChatGPT, or Gemini before you paste it in.