webdevpuneet.com

Matter.js Stacking Tower Game — Perfect Drops and Wind

Matter.js Stacking Tower Game · Games · Plain HTML, CSS & JS · Live preview

CategoryGames

About this UI Snippet

A Physics Stacking Game in Matter.js — Pendulum Drops, Perfect Combos, Wind and a Rising Camera

Screenshot of the Matter.js Stacking Tower Game snippet rendered live

Stacking games look simple: drop a block and don't let the tower fall. Underneath they depend on real physics, because floors that land off-centre tip and a tall stack sways. Matter.js handles that, and this snippet adds the game around it: a pendulum that swings each new floor, a Perfect-landing combo, wind that pushes falling floors sideways, lives, a score and best saved in localStorage, particles, and a camera that climbs from dusk into a starry sky. It is all plain JavaScript on one canvas.

A pendulum that is not a physics body

While it hangs, the next floor is only a position: an angle that follows a sine of phase, converted to x = centre + sin(theta) * length and y = pivot + cos(theta) * length, with the floor tilted against the swing. Keeping it out of the physics world means nothing can knock it. The phase is accumulated each step, so speeding the swing up as the tower grows never makes the floor jump, and the swing gets wider as well as faster.

Dropping honestly

On click, tap or Space the floor becomes a real rectangle at the same position and tilt and falls straight down. Carrying over the swing's sideways speed looks realistic but drifts the block far from the faint drop guide over a long fall, so timing is the skill. The fall speed is also capped (MAX_FALL, 6px per step): a long drop at full speed hits the stack hard enough to shake a tall tower apart. Floors also get narrower as the tower grows, down to 70px.

Perfect landings and combos

Once a floor is asleep, or slow after the first 30 steps, it counts as landed and judge() compares it with the floor beneath (or the base). Within 8px of centre and nearly level it is Perfect: the combo rises, the floor glows, gold sparks fire and the bonus is 25 times the combo on top of 10 points. Any other landing resets the combo and kicks up dust.

Wind

From the fifth floor, a gust target is picked every few seconds and the wind eases toward it. It is applied as a small Body.applyForce to floors that have not landed, so it only matters while a floor is falling; the drop guide leans with the gust and a meter in the corner shows the strength. Wind never touches landed floors, which keeps tall towers stable.

Stable stacking

Tall stacks are a stress test for a 2D engine, so the snippet raises positionIterations and velocityIterations, uses high static friction and zero restitution, and turns on enableSleeping so settled floors stop jittering. A floor that falls below the base platform or off its sides costs a life.

Built for phones

The board keeps its 3:4 shape and scales with CSS, so the canvas stays sharp (it renders at the device pixel ratio) while the whole game is sized to the screen height with 100dvh: HUD, board and hint fit without scrolling. The canvas uses touch-action: none and any touch drops the floor at once, with no double-tap zoom delay or page scroll. On a sideways phone the HUD moves to a column beside a full-height board, buttons grow to 44 px tall on coarse pointers, safe-area insets keep it clear of notches, and Perfect landings and lost floors give a short vibration where the device supports it.

A camera that climbs

With hasBounds, the renderer draws only what is inside render.bounds, whose vertical position eases toward the tower top. Everything else is painted by hand in afterRender: floors with lit windows, the podium, height lines every 5 m, and the background last with destination-over, where the sky fades from dusk to deep space and the stars twinkle more with altitude.

What's included

Features

Real pendulum swing
Position from sin and cos of an angle, with accumulated phase so speed changes never jump.
Perfect combos
A centred, level landing earns 25 points times the combo, with a glow and sparks.
Wind
Gusts push falling floors only, shown by a meter and a leaning drop guide.
Stable stacking
Extra solver iterations, high friction, zero restitution and sleeping bodies.
Rising camera
Eased render.bounds keeps the tower top in view as it grows.
Dusk to night sky
Gradient, twinkling stars and moon change with altitude, painted with destination-over.
Lives, score and best
Three lives, floors and combos scored, and the best saved in localStorage.
Phone-ready layout
Fits the screen height, switches to a side HUD in landscape, has 44px buttons, safe-area padding and haptic feedback.

Step by step

How to Use

  1. 1
    Press Start buildingThe card explains the goal. Press the button or Space to begin, and the first floor swings on its rope above the tower.
  2. 2
    Time the dropClick, tap anywhere on the tower, or press Space. The floor falls straight down; the faint column below it shows where it will land.
  3. 3
    Land it centredWithin 8px of the floor below and level counts as Perfect: a glow, gold sparks and a combo bonus that grows with each one.
  4. 4
    Watch the windFrom the fifth floor the wind meter appears. A strong gust pushes the falling floor sideways, so aim against it.
  5. 5
    Keep your livesA floor that falls off the base costs one of three hearts and resets your combo. Climb as the camera rises into the stars.
  6. 6
    Beat your bestYour best score is saved on this device, so there is always a record to beat.

Real-world uses

Common Use Cases

Casual web games
Ship a one-button game for any device: a pendulum drop, Perfect combos and a saved best score give it a reason to replay.
Game-jam starter
Build on the existing lives, wind and combos with power-ups, themes or block shapes instead of starting the loop and camera from scratch.
Matter.js stability lessons
Study the combination that keeps tall stacks still: extra iterations, friction, zero restitution and sleeping, with landing detection on top.
Branded mini-game
Swap floors for your product boxes or logo blocks, the skyline for your brand colours, and the results card for a call to action.
Balance and centre-of-mass demos
Show why off-centre blocks tip, using the Perfect threshold and the narrower floors to make the effect easy to see.

Got questions?

Frequently Asked Questions

Yes. The board scales to the screen height so nothing scrolls, any tap on it drops the floor immediately, the HUD moves beside the board in landscape, and Perfect landings and lost floors vibrate on devices that allow it. Space and click still work on a desktop.

Raise engine.positionIterations and velocityIterations, use high friction and frictionStatic, zero restitution, and enable sleeping so settled bodies stop jittering. Keep wind or other forces off bodies that have already landed.

So nothing can collide with it while it hangs. On drop you create the body at the same position and angle and let it fall, which keeps the drop guide honest. Accumulating the pendulum phase also lets you change the speed smoothly.

When a floor lands, judge() finds the landed floor directly below it, or the base, and compares x positions. A difference under 8px with an angle under 0.08 radians is Perfect, which raises the combo and adds 25 points per combo level. Other landings reset the combo.

Every step, falling floors get Body.applyForce with a horizontal force of wind times mass times a small constant. The wind value eases toward a new random target every few seconds. Landed floors are skipped, so towers do not slide apart.

Create the renderer with hasBounds: true and move render.bounds.min.y and max.y every frame, easing toward a target based on the tower's highest point. Draw custom graphics with the same vertical offset through setTransform.

Copy & paste

Source Code

Requires
<div class="st">
  <div class="st-hud">
    <div><span>Height</span><b id="stHeight">0 m</b></div>
    <div><span>Score</span><b id="stScore">0</b></div>
    <div><span>Best</span><b id="stBest">0</b></div>
    <div><span>Lives</span><b id="stLives">&#9829;&#9829;&#9829;</b></div>
    <button type="button" id="stRestart">Restart</button>
  </div>
  <div class="st-stage" id="stStage">
    <div class="st-over" id="stOver">
      <strong id="stOverTitle">Skyline</strong>
      <div class="st-stats" id="stStats" hidden></div>
      <span id="stOverText">Drop the swinging floor onto the tower. Land it dead centre for a Perfect and build a combo. Three lost floors and it's over.</span>
      <button type="button" id="stAgain">Start building</button>
    </div>
  </div>
  <p class="st-hint"><span class="st-keys">Click or press <kbd>Space</kbd> to drop.</span><span class="st-tap">Tap the tower to drop.</span> Once it grows, wind pushes falling floors sideways.</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 the hand-off from the animated pendulum floor to a physics body, or how judge() decides whether a landing is Perfect. Since Perfect combos, wind, lives, a saved best and the changing sky already exist, ask for what is missing: power-ups such as a slow-motion swing or a glue block, different floor shapes, a daily seed so everyone gets the same sequence, sound effects on landings, a ghost marker of your best tower, or a leaderboard. It can also check whether the stability settings hold up for towers above fifty floors.

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 physics stacking tower game with Matter.js 0.20 (from a CDN) in plain HTML, CSS and JavaScript.

Requirements:
- A tall canvas with a static base platform; enable sleeping and raise position/velocity iterations. Draw every floor by hand in afterRender (render.visible = false): gradient floors with lit windows, a podium, dashed height lines every 5 m.
- The next floor (random width that shrinks as the tower grows, rotating hue) hangs on a rope from a pendulum above the view: x = centre + sin(theta) * length, y = pivot + cos(theta) * length, theta = amplitude * sin(phase), with phase accumulated each step so speed changes never jump. It is not a physics body until dropped.
- Click, tap or Space drops it: create a rectangle body at the same position and angle with no sideways velocity, high friction and zero restitution. A faint drop guide shows where it will land.
- Cap the fall speed of a dropped floor at 6 px per step (Body.setVelocity) so long drops do not shake the stack. A floor is landed when asleep or slow after 30 steps. Compare it with the floor beneath (or the base): within 8 px of centre and level (angle under 0.08) is Perfect, which raises a combo, adds 10 + 25 * combo points, glows and sprays gold sparks. Other landings reset the combo and kick up dust.
- From the fifth floor, apply wind: a target changes every few seconds, the wind eases toward it, and Body.applyForce pushes only floors that have not landed. Show a wind meter and lean the drop guide.
- A floor that falls off the base costs one of three lives with debris and shake. Game over shows height, floors and score; the best score is saved in localStorage with try/catch.
- A camera using hasBounds that eases upward to keep the tower top in view, and a destination-over background with a sky that fades from dusk to space and twinkling stars that strengthen with altitude.
- HUD with height, score, best and hearts, a start card and a Restart button.
- Make it mobile friendly: size the whole game to 100dvh so it never scrolls, canvas touch-action none with pointerdown to drop, a 44px minimum tap size on coarse pointers, a sideways layout with the HUD in a column, safe-area padding, user-select off, and navigator.vibrate on Perfect and on a lost floor.

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.