Matter.js Hill Climb Car Game — Boost, Coins and Flips
Matter.js Hill Climb Car Game · Games · Plain HTML, CSS & JS · Live preview
About this UI Snippet
Matter.js Hill Climb Car — Suspension, Boost, Coins, Flip Tricks and a Parallax World

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
Step by step
How to Use
- 1Press Start drivingThe start card lists the goal: reach the 500 m summit. Press the button, Enter or → to begin.
- 2Gas, 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.
- 3Lean in the airWith both wheels off the ground the pedals tilt the car. Rotate a full turn and land upright for +100 flip points.
- 4Collect coins and fuelCoins add 10 points each and a little boost. Yellow cans refill the tank, so plan your throttle between them.
- 5Watch the progress barThe bar along the top of the stage shows how far you are from the checkered flag at 500 m.
- 6Beat 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
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
<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">◀ 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 ▶</button>
</div>
</div>
<p class="hc-hint"><kbd>→</kbd>/<kbd>D</kbd> gas · <kbd>←</kbd>/<kbd>A</kbd> brake · <kbd>↑</kbd>/<kbd>Space</kbd> boost · <kbd>R</kbd> restart. Rotate in the air for flip bonuses.</p>
</div>*{box-sizing:border-box;margin:0;padding:0}
body{font-family:system-ui,-apple-system,sans-serif;background:#0c1222;color:#e2e8f0;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:18px}
.hc{width:100%;max-width:960px}
.hc-hud{display:flex;align-items:center;gap:18px;margin-bottom:10px;flex-wrap:wrap}
.hc-hud>div{display:flex;flex-direction:column;gap:2px}
.hc-hud span{font-size:10.5px;text-transform:uppercase;letter-spacing:.08em;color:#94a3b8;font-weight:700}
.hc-hud b{font:800 19px ui-monospace,monospace;color:#fde047;font-variant-numeric:tabular-nums}
.hc-meter i{display:block;width:110px;height:11px;border-radius:99px;background:#1e293b;overflow:hidden;margin-top:6px}
.hc-meter em{display:block;height:100%;width:100%;background:linear-gradient(90deg,#ef4444,#f59e0b 35%,#22c55e);transition:width .15s}
.hc-meter.boost em{background:linear-gradient(90deg,#6366f1,#38bdf8)}
.hc-btns{margin-left:auto;display:flex!important;flex-direction:row!important;gap:8px}
.hc-hud button,.hc-over button{border:0;border-radius:10px;background:#f59e0b;color:#1c1917;font:800 12.5px system-ui;padding:9px 16px;cursor:pointer}
.hc-hud #hcSound{background:#1e293b;color:#cbd5e1}
.hc-hud #hcSound[aria-pressed="true"]{background:#22c55e;color:#052e16}
.hc :focus-visible{outline:2px solid #fde047;outline-offset:2px}
.hc-stage{position:relative;border-radius:18px;overflow:hidden;border:1px solid #1e293b}
.hc-stage canvas{display:block;width:100%;height:auto}
.hc-prog{position:absolute;left:0;right:0;top:0;height:4px;background:rgba(15,23,42,.35);z-index:2}
.hc-prog i{display:block;height:100%;width:0;background:linear-gradient(90deg,#fde047,#f97316)}
.hc-over{position:absolute;inset:0;z-index:3;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:20px;background:rgba(12,18,34,.5);backdrop-filter:blur(2px);text-align:center}
.hc-over[hidden]{display:none}
.hc-over strong{font-size:36px;color:#fde047;letter-spacing:-.01em;text-shadow:0 3px 0 rgba(0,0,0,.35)}
.hc-over>span{font-size:14px;color:#e2e8f0;max-width:380px;line-height:1.5}
.hc-stats{display:flex;gap:10px}
.hc-stats[hidden]{display:none}
.hc-stats div{background:rgba(15,23,42,.7);border-radius:12px;padding:8px 14px}
.hc-stats small{display:block;font-size:10px;text-transform:uppercase;letter-spacing:.08em;color:#94a3b8;font-weight:700}
.hc-stats b{font:800 18px ui-monospace,monospace;color:#fde047}
.hc-over button{margin-top:4px;padding:11px 22px;font-size:14px}
.hc-pedals{position:absolute;left:12px;right:12px;bottom:12px;display:flex;justify-content:space-between;gap:10px;pointer-events:none;z-index:2}
.hc-pedal{pointer-events:auto;border:0;border-radius:14px;background:rgba(15,23,42,.72);color:#fff;font:800 14px system-ui;padding:16px 22px;cursor:pointer;user-select:none;-webkit-user-select:none;touch-action:none;display:inline-flex;align-items:center;gap:6px}
.hc-pedal.gas{background:rgba(22,163,74,.85)}
.hc-pedal.boost{background:rgba(79,70,229,.85);margin:0 auto}
.hc-pedal.on{transform:scale(.95);filter:brightness(1.25)}
.hc-hint{font-size:12px;color:#94a3b8;margin-top:8px;text-align:center}
.hc kbd{font:700 11px ui-monospace,monospace;background:#1e293b;border:1px solid #334155;border-radius:5px;padding:1px 5px}var M = Matter, Engine = M.Engine, Render = M.Render, Runner = M.Runner, Bodies = M.Bodies, Body = M.Body,
Composite = M.Composite, Constraint = M.Constraint, Events = M.Events;
var W = 960, H = 480;
var PX_PER_M = 40;
var FINISH_M = 500;
var engine = Engine.create();
engine.gravity.y = 1;
engine.positionIterations = 10;
engine.velocityIterations = 8;
var render = Render.create({
element: document.getElementById('hcStage'),
engine: engine,
options: { width: W, height: H, wireframes: false, background: 'transparent', pixelRatio: window.devicePixelRatio || 1, hasBounds: true },
});
document.getElementById('hcStage').prepend(render.canvas);
var $ = function (id) { return document.getElementById(id); };
// ---------- Terrain ----------
// Rolling hills from summed sine waves that get steeper with distance. The ground is a chain of thin
// static rectangles, each rotated to match the slope between two sample points (no poly-decomp needed).
var SEG = 40, SEGMENTS = 520;
function groundY(x) {
var d = Math.max(0, x - 500) / 4000;
var amp = Math.min(1, d) * 1.6 + 0.25;
return 360
- Math.sin(x / 260) * 45 * amp
- Math.sin(x / 97 + 1.3) * 16 * amp
- Math.sin(x / 610 + 0.4) * 70 * amp;
}
var terrain = [], groundPts = [];
function buildTerrain() {
groundPts = [];
for (var i = 0; i <= SEGMENTS; i++) groundPts.push({ x: i * SEG - 200, y: groundY(i * SEG - 200) });
for (i = 0; i < SEGMENTS; i++) {
var a = groundPts[i], b = groundPts[i + 1];
var len = Math.hypot(b.x - a.x, b.y - a.y);
var ang = Math.atan2(b.y - a.y, b.x - a.x);
var cx = (a.x + b.x) / 2 - Math.sin(ang) * -10, cy = (a.y + b.y) / 2 + Math.cos(ang) * 10;
terrain.push(Bodies.rectangle(cx, cy, len + 2, 20, { isStatic: true, angle: ang, friction: 1, label: 'ground', render: { visible: false } }));
}
terrain.push(Bodies.rectangle(-220, 200, 40, 600, { isStatic: true, render: { visible: false } }));
Composite.add(engine.world, terrain);
}
// ---------- Car ----------
// A chassis, a head and two wheels joined by springy constraints (the suspension). All parts share a negative
// collision group. Driving = easing the wheels' angular velocity; wheel friction does the rest.
var car, chassis, wheelA, wheelB, head;
function buildCar(x, y) {
var group = Body.nextGroup(true);
chassis = Bodies.rectangle(x, y, 120, 26, { collisionFilter: { group: group }, density: 0.002, chamfer: { radius: 8 }, label: 'chassis', render: { visible: false } });
head = Bodies.circle(x - 6, y - 30, 12, { collisionFilter: { group: group }, density: 0.0005, label: 'head', render: { visible: false } });
wheelA = Bodies.circle(x - 42, y + 24, 21, { collisionFilter: { group: group }, friction: 1, frictionStatic: 10, density: 0.0016, restitution: 0.1, render: { visible: false } });
wheelB = Bodies.circle(x + 42, y + 24, 21, { collisionFilter: { group: group }, friction: 1, frictionStatic: 10, density: 0.0016, restitution: 0.1, render: { visible: false } });
function axle(wheel, offX) {
return [
Constraint.create({ bodyA: chassis, pointA: { x: offX, y: 10 }, bodyB: wheel, stiffness: 0.3, damping: 0.12, length: 16, render: { visible: false } }),
Constraint.create({ bodyA: chassis, pointA: { x: offX + (offX < 0 ? 30 : -30), y: 0 }, bodyB: wheel, stiffness: 0.25, damping: 0.1, render: { visible: false } }),
];
}
var neck = Constraint.create({ bodyA: chassis, pointA: { x: -6, y: -14 }, bodyB: head, stiffness: 0.9, length: 16, render: { visible: false } });
var neck2 = Constraint.create({ bodyA: chassis, pointA: { x: 14, y: -10 }, bodyB: head, stiffness: 0.9, render: { visible: false } });
car = Composite.create({ label: 'car' });
Composite.add(car, [chassis, head, wheelA, wheelB, neck, neck2].concat(axle(wheelA, -42), axle(wheelB, 42)));
Composite.add(engine.world, car);
}
// ---------- Pickups ----------
var cans = [], coins = [];
function buildPickups() {
cans = []; coins = [];
var END = SEGMENTS * SEG - 400;
for (var x = 1400; x < END; x += 1100 + Math.random() * 500) {
cans.push(Bodies.rectangle(x, groundY(x) - 34, 24, 30, { isStatic: true, isSensor: true, label: 'fuel', render: { visible: false } }));
}
Composite.add(engine.world, cans);
// Arcs of coins that follow the hills, the middle of each arc floating higher (worth a jump)
for (var s = 700, id = 0; s < END; s += 520 + Math.random() * 320) {
var n = 5 + Math.floor(Math.random() * 3);
for (var j = 0; j < n; j++) {
var cx = s + j * 38;
coins.push({ x: cx, y: groundY(cx) - 46 - Math.sin(j / (n - 1) * Math.PI) * 38, taken: false, i: id++ });
}
}
}
// ---------- Effects: particles, floating text, screen shake ----------
var particles = [], texts = [], shake = 0;
function burst(x, y, color, n, speed, life, grav) {
for (var i = 0; i < n && particles.length < 320; i++) {
var a = Math.random() * Math.PI * 2, v = Math.random() * speed;
particles.push({ x: x, y: y, vx: Math.cos(a) * v, vy: Math.sin(a) * v - 0.6, g: grav, life: life * (0.6 + Math.random() * 0.4), max: life, r: 2 + Math.random() * 2.5, c: color });
}
}
function floatText(x, y, text, color) { texts.push({ x: x, y: y, text: text, color: color, life: 70 }); }
// ---------- Sound (off until you press the button) ----------
var audio = null, engOsc = null, engGain = null, soundOn = false;
function setSound(on) {
soundOn = on;
if (on && !audio) {
try {
audio = new (window.AudioContext || window.webkitAudioContext)();
engOsc = audio.createOscillator(); engOsc.type = 'sawtooth';
var lp = audio.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 520;
engGain = audio.createGain(); engGain.gain.value = 0;
engOsc.connect(lp); lp.connect(engGain); engGain.connect(audio.destination); engOsc.start();
} catch (e) { audio = null; soundOn = false; }
}
if (audio) soundOn ? audio.resume() : engGain.gain.setTargetAtTime(0, audio.currentTime, 0.05);
$('hcSound').textContent = soundOn ? 'Sound on' : 'Sound off';
$('hcSound').setAttribute('aria-pressed', String(soundOn));
}
function beep(freq, ms, type, vol) {
if (!soundOn || !audio) return;
var o = audio.createOscillator(), g = audio.createGain();
o.type = type || 'sine'; o.frequency.value = freq;
g.gain.setValueAtTime(vol || 0.08, audio.currentTime);
g.gain.exponentialRampToValueAtTime(0.0001, audio.currentTime + ms / 1000);
o.connect(g); g.connect(audio.destination); o.start(); o.stop(audio.currentTime + ms / 1000);
}
function engineSound(drive, boosting) {
if (!audio || !soundOn) return;
var t = audio.currentTime;
engOsc.frequency.setTargetAtTime(48 + Math.abs(chassis.velocity.x) * 13 + (drive ? 28 : 0) + (boosting ? 45 : 0), t, 0.05);
engGain.gain.setTargetAtTime(over ? 0 : drive ? 0.05 : 0.02, t, 0.08);
}
// ---------- State ----------
var input = { gas: false, brake: false, boost: false };
var fuel, boost, coinCount, bonus, best = 0, over, ready, startX, flippedFor, airSpin, lastAngle, wasAir;
try { best = +localStorage.getItem('hc-best') || 0; } catch (e) {}
function score() { return Math.max(0, Math.round((chassis.position.x - startX) / PX_PER_M)) + coinCount * 10 + bonus; }
function reset(intro) {
Composite.clear(engine.world, false);
terrain = []; particles = []; texts = [];
buildTerrain();
buildCar(120, groundY(120) - 60);
buildPickups();
fuel = 1; boost = 1; coinCount = 0; bonus = 0; shake = 0;
startX = chassis.position.x; flippedFor = 0; airSpin = 0; lastAngle = 0; wasAir = false;
over = !!intro; ready = !!intro;
var ov = $('hcOver');
if (intro) {
$('hcOverTitle').textContent = 'Hill Climb';
$('hcOverText').textContent = 'Reach the ' + FINISH_M + ' m summit. Collect coins and fuel, pull off flips in the air, and keep your head off the ground.';
$('hcStats').hidden = true;
$('hcAgain').textContent = 'Start driving';
}
ov.hidden = !intro;
}
function gameOver(title, text, win) {
if (over) return;
over = true;
var sc = score(), isBest = sc > best;
if (isBest) { best = sc; try { localStorage.setItem('hc-best', String(best)); } catch (e) {} }
if (!win) { shake = 16; burst(chassis.position.x, chassis.position.y, '#f97316', 40, 7, 40, 0.18); burst(chassis.position.x, chassis.position.y, '#fde047', 20, 5, 30, 0.15); beep(110, 450, 'square', 0.1); }
else { for (var i = 0; i < 4; i++) burst(chassis.position.x + (i - 1.5) * 40, chassis.position.y - 60, ['#fde047', '#f97316', '#38bdf8', '#4ade80'][i], 25, 6, 50, 0.12); beep(660, 300, 'triangle', 0.1); }
$('hcOverTitle').textContent = title;
$('hcOverText').textContent = text + (isBest ? ' New best score!' : '');
var d = Math.max(0, Math.round((chassis.position.x - startX) / PX_PER_M));
$('hcStats').innerHTML = '<div><small>Distance</small><b>' + d + ' m</b></div><div><small>Coins</small><b>' + coinCount + '</b></div><div><small>Score</small><b>' + sc + '</b></div>';
$('hcStats').hidden = false;
$('hcAgain').textContent = 'Drive again';
setTimeout(function () { $('hcOver').hidden = false; }, win ? 400 : 650);
}
function go() {
if (ready) { ready = false; over = false; startX = chassis.position.x; $('hcOver').hidden = true; }
else reset(false);
}
Events.on(engine, 'collisionStart', function (e) {
e.pairs.forEach(function (p) {
var labels = [p.bodyA.label, p.bodyB.label];
var can = p.bodyA.label === 'fuel' ? p.bodyA : p.bodyB.label === 'fuel' ? p.bodyB : null;
if (can && !can.taken) {
can.taken = true; fuel = 1; Composite.remove(engine.world, can);
burst(can.position.x, can.position.y, '#facc15', 18, 4, 30, 0.1);
floatText(can.position.x, can.position.y - 20, 'Fuel full', '#fde047'); beep(520, 160, 'triangle');
}
if (!over && labels.indexOf('head') > -1 && labels.indexOf('ground') > -1) gameOver('Ouch!', 'Your head hit the ground.');
});
});
function touching(w) { return M.Query.collides(w, terrain).length > 0; }
function landed() {
if (Math.cos(chassis.angle) > 0 && Math.abs(airSpin) > 5.4) {
var n = Math.max(1, Math.floor(Math.abs(airSpin) / (Math.PI * 2) + 0.25)), pts = n * 100;
bonus += pts;
floatText(chassis.position.x, chassis.position.y - 70, (airSpin > 0 ? 'Front flip' : 'Back flip') + (n > 1 ? ' x' + n : '') + ' +' + pts, '#38bdf8');
burst(chassis.position.x, chassis.position.y, '#38bdf8', 22, 5, 35, 0.1); beep(740, 220, 'triangle');
}
}
var MAX_SPIN = 0.42;
Events.on(engine, 'beforeUpdate', function () {
// Particles and floating text keep moving even after a crash
for (var i = particles.length - 1; i >= 0; i--) {
var p = particles[i]; p.x += p.vx; p.y += p.vy; p.vy += p.g; if (--p.life <= 0) particles.splice(i, 1);
}
for (i = texts.length - 1; i >= 0; i--) { texts[i].y -= 0.7; if (--texts[i].life <= 0) texts.splice(i, 1); }
if (over) { engineSound(0, false); return; }
var drive = fuel > 0 ? (input.gas ? 1 : input.brake ? -1 : 0) : 0;
var boosting = input.boost && boost > 0 && fuel > 0;
if (boosting && drive === 0) drive = 1;
var target = drive * MAX_SPIN * (boosting ? 1.7 : 1);
var gA = touching(wheelA), gB = touching(wheelB), airborne = !gA && !gB;
[wheelA, wheelB].forEach(function (w, k) {
if (drive !== 0) Body.setAngularVelocity(w, w.angularVelocity + (target - w.angularVelocity) * 0.12);
// dust kicked up by a driven wheel on the ground
if (drive !== 0 && (k ? gB : gA) && Math.abs(w.angularVelocity) > 0.12 && Math.random() < 0.5) {
burst(w.position.x - drive * 14, w.position.y + 18, 'rgba(214,186,140,.7)', 1, 1.6, 22, -0.01);
}
});
// In the air the pedals tilt the car, the classic hill-climb trick
var tilt = fuel > 0 ? (input.gas ? 1 : input.brake ? -1 : 0) : 0;
if (airborne && tilt !== 0) Body.setAngularVelocity(chassis, chassis.angularVelocity - tilt * 0.006);
if (boosting) {
Body.applyForce(chassis, chassis.position, { x: Math.cos(chassis.angle) * 0.006, y: Math.sin(chassis.angle) * 0.006 });
boost = Math.max(0, boost - 0.0055);
var bx = chassis.position.x - Math.cos(chassis.angle) * 64, by = chassis.position.y - Math.sin(chassis.angle) * 64 + 6;
burst(bx, by, Math.random() < 0.5 ? '#fb923c' : '#fde047', 2, 2.2, 16, 0);
} else boost = Math.min(1, boost + 0.0012);
if (drive !== 0) fuel = Math.max(0, fuel - (boosting ? 0.0016 : 0.0009));
// Flip tracking: add up the rotation while both wheels are off the ground
if (airborne) airSpin += chassis.angle - lastAngle;
else { if (wasAir) landed(); airSpin = 0; }
lastAngle = chassis.angle; wasAir = airborne;
// Coins
coins.forEach(function (c) {
if (c.taken || Math.abs(c.x - chassis.position.x) > 90) return;
var hit = Math.hypot(c.x - chassis.position.x, c.y - chassis.position.y) < 42 ||
Math.hypot(c.x - wheelA.position.x, c.y - wheelA.position.y) < 34 || Math.hypot(c.x - wheelB.position.x, c.y - wheelB.position.y) < 34;
if (hit) { c.taken = true; coinCount++; boost = Math.min(1, boost + 0.04); burst(c.x, c.y, '#fde047', 8, 3, 22, 0.05); beep(880 + (coinCount % 5) * 60, 90, 'square', 0.04); }
});
var up = Math.cos(chassis.angle);
flippedFor = up < -0.2 ? flippedFor + 1 : 0;
if (flippedFor > 90) gameOver('Flipped!', 'Keep the car upright on steep hills.');
else if (fuel <= 0 && Math.abs(chassis.velocity.x) < 0.05) gameOver('Out of fuel', 'Grab the yellow cans to refuel.');
else if ((chassis.position.x - startX) / PX_PER_M >= FINISH_M) gameOver('Summit reached!', 'You drove all ' + FINISH_M + ' m.', true);
engineSound(drive, boosting);
});
// ---------- Camera (eased render.bounds) with screen shake ----------
var cam = { x: 0, y: 0 };
Events.on(render, 'beforeRender', function () {
var tx = chassis.position.x - W * 0.33 + Math.max(0, chassis.velocity.x) * 6, ty = chassis.position.y - H * 0.6;
cam.x += (tx - cam.x) * 0.12;
cam.y += (ty - cam.y) * 0.08;
shake *= 0.9;
var sx = (Math.random() - 0.5) * shake, sy = (Math.random() - 0.5) * shake;
render.bounds.min.x = cam.x + sx; render.bounds.max.x = cam.x + sx + W;
render.bounds.min.y = cam.y + sy; render.bounds.max.y = cam.y + sy + H;
});
function drawWheel(ctx, w) {
ctx.save();
ctx.translate(w.position.x, w.position.y); ctx.rotate(w.angle);
ctx.fillStyle = '#0f172a'; ctx.beginPath(); ctx.arc(0, 0, 21, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = '#334155'; ctx.lineWidth = 3;
for (var t = 0; t < 12; t++) { ctx.rotate(Math.PI / 6); ctx.beginPath(); ctx.moveTo(17, 0); ctx.lineTo(21, 0); ctx.stroke(); }
ctx.fillStyle = '#cbd5e1'; ctx.beginPath(); ctx.arc(0, 0, 11, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = '#64748b'; ctx.lineWidth = 2.5;
for (var i = 0; i < 3; i++) { ctx.rotate(Math.PI / 3); ctx.beginPath(); ctx.moveTo(-10, 0); ctx.lineTo(10, 0); ctx.stroke(); }
ctx.fillStyle = '#475569'; ctx.beginPath(); ctx.arc(0, 0, 3, 0, Math.PI * 2); ctx.fill();
ctx.restore();
}
function drawCar(ctx) {
ctx.save();
ctx.translate(chassis.position.x, chassis.position.y); ctx.rotate(chassis.angle);
var g = ctx.createLinearGradient(0, -13, 0, 13); g.addColorStop(0, '#f87171'); g.addColorStop(1, '#b91c1c');
ctx.fillStyle = g; ctx.beginPath(); ctx.roundRect(-60, -13, 120, 26, 8); ctx.fill();
ctx.fillStyle = 'rgba(0,0,0,.22)'; ctx.fillRect(-60, 6, 120, 7);
ctx.fillStyle = '#fde68a'; ctx.beginPath(); ctx.roundRect(52, -9, 8, 8, 2); ctx.fill();
ctx.fillStyle = '#e2e8f0'; ctx.fillRect(56, 5, 6, 5); // bumper
ctx.fillStyle = '#334155'; ctx.fillRect(-66, 3, 10, 5); // exhaust
ctx.fillStyle = 'rgba(255,255,255,.28)'; ctx.fillRect(-52, -10, 64, 3); // shine line
ctx.fillStyle = '#1f2937'; ctx.fillRect(18, -30, 6, 18); // windshield post
ctx.restore();
ctx.save();
ctx.translate(head.position.x, head.position.y); ctx.rotate(chassis.angle);
ctx.fillStyle = '#fcd34d'; ctx.beginPath(); ctx.arc(0, 0, 12, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#2563eb'; ctx.beginPath(); ctx.arc(0, -3, 12.5, Math.PI, 0); ctx.fill();
ctx.fillStyle = '#93c5fd'; ctx.fillRect(2, -4, 10, 4);
ctx.fillStyle = '#111'; ctx.beginPath(); ctx.arc(5, 2, 1.8, 0, Math.PI * 2); ctx.fill();
ctx.restore();
}
function hillLayer(ctx, color, par, base, a1, w1, a2, w2, bx) {
ctx.fillStyle = color; ctx.beginPath(); ctx.moveTo(0, H);
for (var x = 0; x <= W; x += 16) ctx.lineTo(x, base - Math.sin((x + bx * par) / w1) * a1 - Math.sin((x + bx * par) / w2) * a2);
ctx.lineTo(W, H); ctx.fill();
}
Events.on(render, 'afterRender', function () {
var ctx = render.context, pr = render.options.pixelRatio, b = render.bounds;
ctx.save();
ctx.setTransform(pr, 0, 0, pr, -b.min.x * pr, -b.min.y * pr);
// Ground fill, a darker lip under the grass, and the grass edge
var i0 = Math.max(0, Math.floor((b.min.x + 200) / SEG) - 1), i1 = Math.min(groundPts.length - 1, i0 + Math.ceil(W / SEG) + 3);
ctx.beginPath(); ctx.moveTo(groundPts[i0].x, b.max.y + 50);
for (var i = i0; i <= i1; i++) ctx.lineTo(groundPts[i].x, groundPts[i].y);
ctx.lineTo(groundPts[i1].x, b.max.y + 50); ctx.closePath();
var g = ctx.createLinearGradient(0, b.min.y, 0, b.max.y + 50);
g.addColorStop(0, '#7c4a1f'); g.addColorStop(1, '#3f2410');
ctx.fillStyle = g; ctx.fill();
ctx.beginPath();
for (i = i0; i <= i1; i++) ctx[i === i0 ? 'moveTo' : 'lineTo'](groundPts[i].x, groundPts[i].y + 11);
ctx.strokeStyle = 'rgba(0,0,0,.2)'; ctx.lineWidth = 4; ctx.lineJoin = 'round'; ctx.stroke();
ctx.beginPath();
for (i = i0; i <= i1; i++) ctx[i === i0 ? 'moveTo' : 'lineTo'](groundPts[i].x, groundPts[i].y);
ctx.strokeStyle = '#4ade80'; ctx.lineWidth = 8; ctx.stroke();
// Distance markers every 50 m, and the finish flag
ctx.fillStyle = 'rgba(255,255,255,.75)'; ctx.font = '700 12px system-ui'; ctx.textAlign = 'center';
for (var m = 50; m < FINISH_M; m += 50) {
var mx = startX + m * PX_PER_M;
if (mx < b.min.x - 40 || mx > b.max.x + 40) continue;
var my = groundY(mx);
ctx.fillRect(mx - 1.5, my - 44, 3, 44);
ctx.fillText(m + ' m', mx, my - 50);
}
var fx = startX + FINISH_M * PX_PER_M;
if (fx > b.min.x - 80 && fx < b.max.x + 80) {
var fy = groundY(fx);
ctx.fillStyle = '#e2e8f0'; ctx.fillRect(fx - 2, fy - 120, 4, 120);
for (var r = 0; r < 4; r++) for (var c = 0; c < 6; c++) { ctx.fillStyle = (r + c) % 2 ? '#0f172a' : '#fff'; ctx.fillRect(fx + c * 9, fy - 120 + r * 9, 9, 9); }
}
// Fuel cans and spinning coins
cans.forEach(function (cn) {
if (cn.taken) return;
ctx.save(); ctx.translate(cn.position.x, cn.position.y + Math.sin(Date.now() / 250) * 3);
ctx.fillStyle = '#facc15'; ctx.fillRect(-12, -15, 24, 30);
ctx.fillStyle = '#b91c1c'; ctx.fillRect(-12, -4, 24, 8);
ctx.fillStyle = '#facc15'; ctx.fillRect(-4, -21, 8, 6);
ctx.restore();
});
var t = Date.now();
coins.forEach(function (cn) {
if (cn.taken || cn.x < b.min.x - 20 || cn.x > b.max.x + 20) return;
var w = 2 + 8 * Math.abs(Math.cos(t / 260 + cn.i * 0.7));
ctx.fillStyle = '#f59e0b'; ctx.beginPath(); ctx.ellipse(cn.x, cn.y, w + 1.5, 10.5, 0, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#fde047'; ctx.beginPath(); ctx.ellipse(cn.x, cn.y, w, 8.5, 0, 0, Math.PI * 2); ctx.fill();
});
// Particles (dust, flames, sparks) behind the car, then the car
particles.forEach(function (p) {
ctx.globalAlpha = Math.max(0, p.life / p.max); ctx.fillStyle = p.c;
ctx.beginPath(); ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2); ctx.fill();
});
ctx.globalAlpha = 1;
drawWheel(ctx, wheelA); drawWheel(ctx, wheelB); drawCar(ctx);
// Floating texts
ctx.font = '800 15px system-ui'; ctx.textAlign = 'center';
texts.forEach(function (tx) {
ctx.globalAlpha = Math.min(1, tx.life / 25); ctx.fillStyle = 'rgba(0,0,0,.4)'; ctx.fillText(tx.text, tx.x + 1, tx.y + 2);
ctx.fillStyle = tx.color; ctx.fillText(tx.text, tx.x, tx.y);
});
ctx.restore();
// Background, painted behind everything drawn so far (nearest layer first)
ctx.save();
ctx.setTransform(pr, 0, 0, pr, 0, 0);
ctx.globalCompositeOperation = 'destination-over';
hillLayer(ctx, '#3f7d5a', 0.5, 305, 24, 150, 9, 47, b.min.x);
hillLayer(ctx, '#6f9bc2', 0.22, 235, 55, 210, 18, 90, b.min.x);
ctx.fillStyle = 'rgba(255,255,255,.85)';
for (var k = 0; k < 5; k++) {
var cx = (((k * 300 - b.min.x * 0.12) % (W + 300)) + (W + 300)) % (W + 300) - 150, cy = 55 + (k * 37) % 70;
ctx.beginPath(); ctx.ellipse(cx, cy, 46, 14, 0, 0, Math.PI * 2); ctx.ellipse(cx + 28, cy - 9, 30, 13, 0, 0, Math.PI * 2); ctx.ellipse(cx - 26, cy - 5, 26, 11, 0, 0, Math.PI * 2); ctx.fill();
}
var sun = ctx.createRadialGradient(W * 0.78, 90, 4, W * 0.78, 90, 120);
sun.addColorStop(0, 'rgba(255,251,190,1)'); sun.addColorStop(0.25, 'rgba(254,240,138,.85)'); sun.addColorStop(1, 'rgba(254,240,138,0)');
ctx.fillStyle = sun; ctx.fillRect(0, 0, W, H);
var sky = ctx.createLinearGradient(0, 0, 0, H);
sky.addColorStop(0, '#0ea5e9'); sky.addColorStop(1, '#bae6fd');
ctx.fillStyle = sky; ctx.fillRect(0, 0, W, H);
ctx.restore();
// HUD
var dist = Math.max(0, Math.round((chassis.position.x - startX) / PX_PER_M)), sc = score();
if (!over && sc > best) best = sc;
$('hcDist').textContent = dist + ' m';
$('hcCoins').textContent = coinCount;
$('hcScore').textContent = sc;
$('hcBest').textContent = best;
$('hcFuel').style.width = (fuel * 100).toFixed(1) + '%';
$('hcBoost').style.width = (boost * 100).toFixed(1) + '%';
$('hcProg').style.width = Math.min(100, dist / FINISH_M * 100).toFixed(1) + '%';
});
// ---------- Input ----------
function syncPedals() {
$('hcGas').classList.toggle('on', input.gas);
$('hcBrake').classList.toggle('on', input.brake);
$('hcBoostBtn').classList.toggle('on', input.boost);
}
function key(e, down) {
var k = e.key.toLowerCase(), hit = false;
if (k === 'arrowright' || k === 'd') { input.gas = down; hit = true; }
if (k === 'arrowleft' || k === 'a') { input.brake = down; hit = true; }
if (k === 'arrowup' || k === 'w' || k === ' ' || k === 'shift') { input.boost = down; hit = true; }
if (down && k === 'r') { reset(false); hit = true; }
if (down && ready && (k === 'enter' || k === ' ' || k === 'arrowright' || k === 'd')) go();
if (hit) e.preventDefault();
syncPedals();
}
document.addEventListener('keydown', function (e) { key(e, true); });
document.addEventListener('keyup', function (e) { key(e, false); });
window.addEventListener('blur', function () { input.gas = input.brake = input.boost = false; syncPedals(); });
[['hcGas', 'gas'], ['hcBrake', 'brake'], ['hcBoostBtn', 'boost']].forEach(function (p) {
var el = $(p[0]);
el.addEventListener('pointerdown', function (e) { input[p[1]] = true; el.setPointerCapture(e.pointerId); syncPedals(); });
['pointerup', 'pointercancel', 'lostpointercapture'].forEach(function (t) { el.addEventListener(t, function () { input[p[1]] = false; syncPedals(); }); });
});
$('hcReset').addEventListener('click', function () { reset(false); });
$('hcAgain').addEventListener('click', go);
$('hcSound').addEventListener('click', function () { setSound(!soundOn); });
reset(true);
Render.run(render);
Runner.run(Runner.create(), engine);
/* wdp-share:start */
(function () {
var TITLE = 'Matter.js Hill Climb Car Game', URL = 'https://webdevpuneet.com/ui-snippets/matter-js-hill-climb-car/';
if (window.__wdpShare) return;
window.__wdpShare = true;
var blob = null, file = null, lastInfo = null;
/* ---- UI ---- */
var st = document.createElement('style');
st.textContent =
'.wdps-in,.wdps-btn,.wdps-box{touch-action:manipulation;-webkit-tap-highlight-color:transparent}.wdps-in{display:block;margin:12px auto 0;border:0;border-radius:12px;padding:11px 22px;font:800 15px/1 system-ui,sans-serif;background:#16a34a;color:#fff;cursor:pointer;box-shadow:0 3px 0 #11793a;pointer-events:auto;position:relative;z-index:5}' +
'.wdps-in:hover{background:#15803d}.wdps-in:active{transform:translateY(2px);box-shadow:0 1px 0 #11793a}' +
'.wdps-btn{position:fixed;right:12px;bottom:12px;z-index:2147483000;border:0;border-radius:99px;padding:9px 16px;font:700 13px/1 system-ui,sans-serif;background:#16a34a;color:#fff;cursor:pointer;box-shadow:0 3px 12px rgba(0,0,0,.3)}' +
'.wdps-btn.wdps-hot{animation:wdps-p 1.4s ease-in-out infinite}' +
'@keyframes wdps-p{0%,100%{box-shadow:0 0 0 0 rgba(22,163,74,.6),0 3px 12px rgba(0,0,0,.3)}50%{box-shadow:0 0 0 9px rgba(22,163,74,0),0 3px 12px rgba(0,0,0,.3)}}' +
'.wdps-btn:active{transform:translateY(1px)}' +
'.wdps-in[hidden],.wdps-btn[hidden],.wdps-box[hidden],.wdps-box [hidden]{display:none}' +
'.wdps-box{position:fixed;left:50%;bottom:12px;transform:translateX(-50%);z-index:2147483001;width:max-content;max-width:calc(100vw - 24px);box-sizing:border-box;background:#fff;color:#64748b;border:1px solid #d5e2ee;border-radius:12px;padding:8px 12px;font:700 12px/1.4 system-ui,sans-serif;box-shadow:0 8px 26px rgba(15,23,42,.25);display:flex;flex-wrap:wrap;gap:8px;align-items:center}' +
'.wdps-box button,.wdps-box a{border:1px solid #d5e2ee;background:#f8fafc;color:#1e293b;border-radius:99px;padding:5px 12px;font:700 12px system-ui,sans-serif;text-decoration:none;cursor:pointer}' +
'.wdps-box .wdps-x{border:0;background:none;font-size:19px;line-height:1;padding:0 4px;margin-left:auto;color:#475569}' +
'@media (max-width:700px){.wdps-box{width:calc(100vw - 24px);justify-content:center;padding:10px 12px}.wdps-box>span{width:100%;text-align:center}.wdps-box button,.wdps-box a{padding:9px 14px;font-size:13px}.wdps-box .wdps-x{position:absolute;top:4px;right:4px}.wdps-in{width:100%;max-width:320px}}';
document.head.appendChild(st);
var pill = document.createElement('button');
pill.type = 'button'; pill.className = 'wdps-btn'; pill.textContent = 'Share result';
var inl = document.createElement('button');
inl.type = 'button'; inl.className = 'wdps-in'; inl.textContent = 'Share result'; inl.hidden = true;
var box = document.createElement('div');
box.className = 'wdps-box'; box.hidden = true;
box.setAttribute('role', 'dialog'); box.setAttribute('aria-label', 'Share your result');
box.innerHTML =
'<span data-a="msg">Share your result:</span>' +
'<button type="button" data-a="copy">Copy image</button>' +
'<a data-a="dl" download="result.png">Download image</a>' +
'<button type="button" data-a="more" hidden>More…</button>' +
'<a data-a="wa" target="_blank" rel="noopener">WhatsApp</a>' +
'<a data-a="x" target="_blank" rel="noopener">X</a>' +
'<a data-a="fb" target="_blank" rel="noopener">Facebook</a>' +
'<button type="button" class="wdps-x" data-a="close" aria-label="Close share options">×</button>';
document.body.appendChild(box);
document.body.appendChild(pill);
function q(a) { return box.querySelector('[data-a="' + a + '"]'); }
function ours(el) { return el === inl || el === pill || !!el.closest('.wdps-box'); }
/* ---- reading the result from the screen ---- */
function shown(el) {
if (!el || !el.getClientRects().length) return false;
for (var n = el; n && n !== document.body; n = n.parentElement) {
var cs = getComputedStyle(n);
if (cs.display === 'none' || cs.visibility === 'hidden' || parseFloat(cs.opacity) < 0.1) return false;
if (n.hidden || n.getAttribute('aria-hidden') === 'true') return false;
}
return true;
}
function txt(el) { return (el.textContent || '').replace(/\s+/g, ' ').trim(); }
function sig(el) { return ((el.id || '') + ' ' + (typeof el.className === 'string' ? el.className : '')).toLowerCase(); }
var OUTCOME = /(you win|you won|win!|wins|victory|game over|time.?s up|cleared|complete|solved|defeat|you lose|you lost|lost|draw|crash|failed|success|congrat|score|result|finished|beat|all matched|well done|perfect|new best)/i;
var HEADSIG = /(title|headline|msg|message|banner|result|verdict|status)/;
var WIN = /(you win|you won|win!|wins|victory|cleared|complete|solved|success|congrat|beat|matched|perfect|new best|record)/i;
var LOSS = /(game over|time.?s up|defeat|you lose|you lost|lost|crash|failed|out of)/i;
var BOX = /(overlay|modal|banner|result|over|end|dialog|screen|popup|panel|card|finish|win)/;
function readResult() {
var head = '', sub = '', root = null, headEl = null;
var all = document.body.querySelectorAll('h1,h2,h3,h4,p,strong,div,span');
for (var i = 0; i < all.length && !head; i++) {
var el = all[i];
if (ours(el) || el.children.length > 2) continue;
if (!HEADSIG.test(sig(el))) continue;
/* a banner that holds its own title: use the title inside it instead */
var inner = false;
for (var c = 0; c < el.children.length; c++) if (HEADSIG.test(sig(el.children[c]))) inner = true;
if (inner) continue;
var t = txt(el);
if (t.length < 3 || t.length > 70 || !OUTCOME.test(t) || !shown(el)) continue;
head = t; headEl = el; root = el.parentElement;
}
if (root) {
var kids = root.querySelectorAll('p,span,div');
for (var j = 0; j < kids.length && !sub; j++) {
var k = kids[j];
if (ours(k) || k.children.length > 2 || !/(sub|text|summary|note|desc|detail)/.test(sig(k))) continue;
var tt = txt(k);
if (tt && tt !== head && tt.length >= 5 && tt.length <= 160 && shown(k)) sub = tt;
}
}
/* the result screen the button goes into: the nearest overlay / banner / result box around the headline */
var host = null;
for (var n = headEl, d = 0; n && n !== document.body && d < 4; n = n.parentElement, d++) {
if (d > 0 && BOX.test(sig(n)) && n.tagName !== 'BUTTON') { host = n; break; }
}
return { head: head, sub: sub, host: host };
}
var STATRE = /(score|moves|time|wpm|best|level|streak|accuracy|combo|coins|distance|height|points|stars|lives|wins|attempt|guess)/;
function readStats() {
var out = [], seen = {};
var all = document.body.querySelectorAll('span,strong,b,div,p,output');
for (var i = 0; i < all.length && out.length < 4; i++) {
var el = all[i];
if (ours(el) || el.children.length > 1) continue;
if (!STATRE.test(sig(el))) continue;
var t = txt(el);
if (!t || t.length > 28 || !/[0-9]/.test(t) || !shown(el)) continue;
if (!/[a-zA-Z]/.test(t) && el.parentElement) {
var parts = [], ch = el.parentElement.childNodes;
for (var p = 0; p < ch.length; p++) { var pv = (ch[p].textContent || '').replace(/\s+/g, ' ').trim(); if (pv) parts.push(pv); }
var pt = parts.join(' ');
if (pt.length <= 30 && /[a-zA-Z]/.test(pt)) t = pt;
}
var key = t.toLowerCase();
if (seen[key]) continue;
seen[key] = 1; out.push(t);
}
return out;
}
function bestCanvas() {
var cs = document.querySelectorAll('canvas'), best = null, area = 0;
for (var i = 0; i < cs.length; i++) {
var r = cs[i].getBoundingClientRect(), a = r.width * r.height;
if (a > area && a > 8000 && shown(cs[i])) { area = a; best = cs[i]; }
}
return best;
}
/* ---- show the button when a result is on screen ---- */
var lastHost = null, timer = 0;
function sync() {
timer = 0;
var r = readResult();
if (r.head && r.host) {
if (inl.parentElement !== r.host) r.host.appendChild(inl);
if (inl.hidden) inl.hidden = false;
if (!pill.hidden) pill.hidden = true;
} else {
if (!inl.hidden) inl.hidden = true;
if (pill.hidden) pill.hidden = false;
pill.classList.toggle('wdps-hot', !!r.head);
}
if (lastHost && !r.head && !box.hidden) box.hidden = true;
lastHost = r.head ? (r.host || document.body) : null;
}
function later() { if (!timer) timer = setTimeout(sync, 200); }
try {
new MutationObserver(function (list) {
for (var i = 0; i < list.length; i++) {
var t = list[i].target;
if (t.nodeType !== 1) t = t.parentElement;
if (t && !ours(t)) { later(); return; }
}
}).observe(document.body, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ['class', 'style', 'hidden'] });
} catch (e) {}
setInterval(later, 1500);
later();
/* ---- the card (1080 x 1080, drawn in memory, light like Pocket Artillery's) ---- */
var outline = 0;
function put(g, t, x, y) { if (outline) { g.lineJoin = 'round'; g.lineWidth = outline; g.strokeStyle = 'rgba(8,12,28,.85)'; g.strokeText(t, x, y); } g.fillText(t, x, y); }
function wrap(g, text, x, y, maxW, lh, maxLines) {
var words = text.split(' '), line = '', n = 0;
for (var i = 0; i < words.length; i++) {
var tst = line ? line + ' ' + words[i] : words[i];
if (g.measureText(tst).width > maxW && line) {
put(g, line, x, y); y += lh; n++; line = words[i];
if (n >= maxLines - 1) { line = words.slice(i).join(' '); break; }
} else line = tst;
}
if (line) {
while (line.length > 3 && g.measureText(line).width > maxW) line = line.slice(0, -2);
put(g, line, x, y); y += lh;
}
return y;
}
/* Biggest-screenshot card: the game frame fills the whole image, the text sits on top of it as an overlay. */
function bgOf(el) {
for (var n = el; n; n = n.parentElement) {
var c = getComputedStyle(n).backgroundColor;
if (c && c !== 'transparent' && c.slice(-4) !== ', 0)') return c;
}
return '#0f172a';
}
function drawBig(info, cv) {
var W = 1080, r = cv.width / cv.height, H = Math.max(810, Math.min(1350, Math.round(W / r)));
var c = document.createElement('canvas'); c.width = W; c.height = H;
var g = c.getContext('2d');
g.fillStyle = bgOf(cv.parentElement || cv); g.fillRect(0, 0, W, H);
var w = W, h = w / r;
if (h > H) { h = H; w = h * r; }
g.imageSmoothingEnabled = true; g.imageSmoothingQuality = 'high';
try { g.drawImage(cv, (W - w) / 2, (H - h) / 2, w, h); } catch (e) { return null; }
/* dark fades under the text so it stays readable on any game colours */
var g1 = g.createLinearGradient(0, 0, 0, H * 0.55); g1.addColorStop(0, 'rgba(8,12,28,.74)'); g1.addColorStop(1, 'rgba(8,12,28,0)');
g.fillStyle = g1; g.fillRect(0, 0, W, H * 0.55);
var g2 = g.createLinearGradient(0, H - 200, 0, H); g2.addColorStop(0, 'rgba(8,12,28,0)'); g2.addColorStop(1, 'rgba(8,12,28,.85)');
g.fillStyle = g2; g.fillRect(0, H - 200, W, 200);
var head = info.head || 'Can you beat me?';
var kind = /draw|tie/i.test(head) ? 'draw' : LOSS.test(head) && !WIN.test(head) ? 'loss' : 'win';
g.textAlign = 'center';
var y = 36;
g.fillStyle = 'rgba(255,255,255,.93)'; g.font = '800 34px system-ui, sans-serif'; outline = 7;
y = wrap(g, TITLE.toUpperCase(), W / 2, y + 34, 1000, 42, 1);
g.fillStyle = kind === 'draw' ? '#e2e8f0' : kind === 'loss' ? '#9db8ff' : '#ffc233';
var big = head.length > 22 ? 84 : 112; g.font = '900 ' + big + 'px system-ui, sans-serif'; outline = 16;
y = wrap(g, head, W / 2, y + big * 0.85, 1000, big * 1.05, 2);
if (info.sub) { g.fillStyle = '#fff'; g.font = '700 40px system-ui, sans-serif'; outline = 9; y = wrap(g, info.sub, W / 2, y + 6, 980, 50, 2); }
outline = 0;
if (info.stats.length) {
g.font = '800 38px system-ui, sans-serif';
var gap = 16, pad = 26, ws = [], tot = -gap;
for (var i = 0; i < info.stats.length; i++) { ws.push(g.measureText(info.stats[i]).width + pad * 2); tot += ws[i] + gap; }
var sc = tot > 960 ? 960 / tot : 1, px = (W - tot * sc) / 2, py = y + 14;
for (var k = 0; k < info.stats.length; k++) {
var w0 = ws[k] * sc;
g.fillStyle = 'rgba(8,12,28,.72)'; g.strokeStyle = 'rgba(255,255,255,.55)'; g.lineWidth = 3;
g.beginPath();
if (g.roundRect) g.roundRect(px, py, w0, 68, 34); else g.rect(px, py, w0, 68);
g.fill(); g.stroke();
g.fillStyle = '#fff'; g.font = '800 ' + Math.round(38 * sc) + 'px system-ui, sans-serif';
g.fillText(info.stats[k], px + w0 / 2, py + 47);
px += w0 + gap * sc;
}
}
outline = 8;
g.fillStyle = '#fff'; g.font = '900 52px system-ui, sans-serif'; put(g, 'Can you beat it?', W / 2, H - 84);
g.fillStyle = 'rgba(255,255,255,.92)'; g.font = '700 34px system-ui, sans-serif'; outline = 6; put(g, 'Play free at webdevpuneet.com', W / 2, H - 34);
outline = 0;
return c;
}
function finish(c, cb) {
var dataUrl = '';
try { dataUrl = c.toDataURL('image/png'); } catch (e) {}
try { c.toBlob(function (b) { cb(b, dataUrl); }, 'image/png'); } catch (e) { cb(null, dataUrl); }
}
function makeCard(info, cb) {
var cv0 = bestCanvas();
if (cv0) { var bc = drawBig(info, cv0); if (bc) { finish(bc, cb); return; } }
var S = 1080, c = document.createElement('canvas');
c.width = S; c.height = S;
var g = c.getContext('2d');
var gr = g.createLinearGradient(0, 0, 0, S);
gr.addColorStop(0, '#eaf4ff'); gr.addColorStop(1, '#fff3ef');
g.fillStyle = gr; g.fillRect(0, 0, S, S);
var cv = bestCanvas();
var head = info.head || 'Can you beat me?';
var kind = /draw|tie/i.test(head) ? 'draw' : LOSS.test(head) && !WIN.test(head) ? 'loss' : 'win';
g.textAlign = 'center';
g.fillStyle = '#1e293b'; g.font = '800 60px system-ui, sans-serif';
var y = wrap(g, TITLE, S / 2, cv ? 120 : 200, 980, 68, 1);
g.fillStyle = kind === 'draw' ? '#475569' : kind === 'loss' ? '#3b63e0' : '#e8553a';
g.font = '800 ' + (head.length > 22 ? 76 : 100) + 'px system-ui, sans-serif';
y = wrap(g, head, S / 2, y + (head.length > 22 ? 70 : 90), 980, head.length > 22 ? 84 : 108, 2);
if (info.sub) { g.fillStyle = '#475569'; g.font = '700 38px system-ui, sans-serif'; y = wrap(g, info.sub, S / 2, y + 4, 940, 48, 2); }
if (info.stats.length) {
g.font = '800 36px system-ui, sans-serif';
var gap = 18, pad = 26, ws = [], tot = -gap;
for (var i = 0; i < info.stats.length; i++) { ws.push(g.measureText(info.stats[i]).width + pad * 2); tot += ws[i] + gap; }
var sc = tot > 1000 ? 1000 / tot : 1, px = (S - tot * sc) / 2, py = y + 14;
for (var k = 0; k < info.stats.length; k++) {
var w0 = ws[k] * sc;
g.fillStyle = '#ffffff'; g.strokeStyle = '#d5e2ee'; g.lineWidth = 3;
g.beginPath();
if (g.roundRect) g.roundRect(px, py, w0, 64, 32); else g.rect(px, py, w0, 64);
g.fill(); g.stroke();
g.fillStyle = '#1e293b'; g.font = '800 ' + Math.round(36 * sc) + 'px system-ui, sans-serif';
g.fillText(info.stats[k], px + w0 / 2, py + 44);
px += w0 + gap * sc;
}
y = py + 64 + 10;
}
if (cv) {
try {
var maxW = 960, maxH = Math.max(180, 930 - y - 30), r = cv.width / cv.height;
var w = maxW, h = w / r;
if (h > maxH) { h = maxH; w = h * r; }
var x = (S - w) / 2, yy = y + 20 + Math.max(0, (maxH - h) / 2);
g.save(); g.shadowColor = 'rgba(60,100,140,0.3)'; g.shadowBlur = 30; g.shadowOffsetY = 10;
g.fillStyle = '#fff'; g.fillRect(x - 8, yy - 8, w + 16, h + 16); g.restore();
g.drawImage(cv, x, yy, w, h);
} catch (e) {}
}
g.fillStyle = '#1e293b'; g.font = '800 46px system-ui, sans-serif';
g.fillText('Can you beat it?', S / 2, 1000);
g.fillStyle = '#64748b'; g.font = '700 34px system-ui, sans-serif';
g.fillText('Play free at webdevpuneet.com', S / 2, 1050);
var dataUrl = '';
try { dataUrl = c.toDataURL('image/png'); } catch (e) {}
try { c.toBlob(function (b) { cb(b, dataUrl); }, 'image/png'); } catch (e) { cb(null, dataUrl); }
}
function shareText(info) {
var bits = [];
if (info.head) bits.push(info.head);
if (info.stats.length) bits.push(info.stats.join(', '));
return TITLE + ': ' + (bits.length ? bits.join(' - ') + '. ' : '') + 'Can you beat it? ' + URL;
}
function msg(t) { q('msg').textContent = t; }
function openFallback() {
var t = encodeURIComponent(shareText(lastInfo));
q('wa').href = 'https://wa.me/?text=' + t;
q('x').href = 'https://twitter.com/intent/tweet?text=' + t;
q('fb').href = 'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(URL) + '"e=' + t;
box.hidden = false;
}
function nativeShare() {
/* a user cancel does nothing; anything else (blocked in an iframe, no permission) shows Copy / Download / links */
try {
navigator.share({ files: [file], title: TITLE, text: shareText(lastInfo) }).catch(function (e) { if (!e || e.name !== 'AbortError') openFallback(); });
} catch (e) { openFallback(); }
}
function onShare() {
var info = readResult(); info.stats = readStats();
lastInfo = info;
msg('Share your result:');
makeCard(info, function (b, dataUrl) {
blob = b; file = null;
if (b) { try { file = new File([b], 'result.png', { type: 'image/png' }); } catch (e) {} }
if (dataUrl) q('dl').href = dataUrl;
q('dl').hidden = !dataUrl;
var canNative = !!(file && navigator.share && navigator.canShare && navigator.canShare({ files: [file] }));
var touch = !!(window.matchMedia && window.matchMedia('(pointer: coarse)').matches);
q('more').hidden = !canNative;
if (canNative && touch) nativeShare();
else openFallback();
});
}
/* Games often have document/window level touch and pointer handlers (some call preventDefault, which cancels the tap's
click on phones, others restart the game on touchstart). So: keep every pointer event on our controls away from the
game, and fire on touchend as well as click (guarded so one tap shares once). */
var busy = 0;
function trigger() { if (busy) return; busy = 1; setTimeout(function () { busy = 0; }, 700); onShare(); }
function guard(el, act) {
var evs = ['pointerdown', 'pointerup', 'mousedown', 'mouseup', 'touchstart', 'touchend', 'click'];
for (var i = 0; i < evs.length; i++) el.addEventListener(evs[i], function (e) { e.stopPropagation(); });
if (act) {
el.addEventListener('touchend', function (e) { if (e.cancelable) e.preventDefault(); act(); });
el.addEventListener('click', function () { act(); });
}
}
guard(pill, trigger);
guard(inl, trigger);
guard(box);
q('more').addEventListener('click', function () { if (file) nativeShare(); });
q('close').addEventListener('click', function () { box.hidden = true; });
document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && !box.hidden) box.hidden = true; });
q('copy').addEventListener('click', function () {
try {
navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]).then(
function () { msg('Image copied. Paste it into your chat or post.'); },
function () { msg('Could not copy here. Try Download image.'); }
);
} catch (e) { msg('Copying images is not supported here. Try Download image.'); }
});
})();
/* wdp-share:end */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:
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.