webdevpuneet.com

Matter.js Slingshot Game — Levels, Critters and Aim Preview

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

CategoryGames

About this UI Snippet

A Slingshot Game in Matter.js — Exact Aim Preview, Fragile Glass and Critters to Pop

Screenshot of the Matter.js Slingshot Tower Knockdown Game snippet rendered live

Pull back, let go, watch a tower collapse: slingshot games are the classic physics-engine showcase. This version turns the mechanics into a small game with three levels, a limited number of stones, green critters to pop, blocks of wood, stone and glass, a dotted aim preview that matches the shot exactly, star ratings and particle effects, all on one canvas with plain JavaScript and Matter.js.

An aim preview that is actually accurate

Instead of letting a spring fling the stone and guessing where it goes, the launch is computed. While you drag, the stone is held at your pointer up to 130px from the anchor. On release, Body.setVelocity gives it a speed of pull distance times a constant (POWER). Because that speed is known, the preview can replay the engine's own per-step maths: multiply by the air friction (1 minus 0.004), add gravity (0.2778 per step), move, and draw a dot every fourth step until the path meets the ground. The dots land where the stone will.

Release detection with enddrag

MouseConstraint fires an enddrag event when you let go. If the dragged body is the stone, the state is "play" and the pull is at least 28px, the spring is detached, the velocity is set and one stone is spent. A smaller pull just lets the spring return it. A new stone is loaded 900ms later with a short grow-in, and startdrag rejects every body that is not the loaded stone.

Three materials

Wood, stone and glass differ in density and fragility. Stone is four times heavier than glass, so it barely moves when hit. Glass shatters when it collides above a speed threshold (lower for another body, higher for the ground), spraying blue shards and giving 50 points, which makes glass floors a way to bring a structure down.

Critters that pop on impact

Each green critter is a circle that pops when something hits it hard enough: the relative speed from collisionStart must exceed 3.6 for a moving body or 7.5 for the ground, so a gentle landing is safe but a falling block is not. A pop gives 500 points, a burst of confetti and a short screen shake. The faces blink, and are drawn along with every other body by hand in afterRender.

Levels, stones and stars

Each level is a function that returns bodies placed relative to the platform: a pillar frame, a two-tower fort with glass and stone floors, and a stepped pyramid built with Composites.pyramid. A level is won when no critters remain and lost when the stones run out and the scene settles. Finishing with two or more stones left earns three stars, and every unused stone is worth 300 bonus points.

Housekeeping

Spent stones are removed once they leave the scene or have lain around for nine seconds, particles and floating text are capped, and the background, clouds and hills are painted last with destination-over.

What's included

Features

Exact aim preview
Velocity is set from the pull, so the dotted path replays the engine's gravity and air friction and matches the shot.
enddrag release
A release with at least 28px of pull launches the stone; smaller pulls return it to the sling.
Wood, stone and glass
Three densities and frictions, with glass shattering above an impact-speed threshold.
Critters that pop
Impact speed from collisionStart decides whether a critter pops, worth 500 points with confetti and shake.
Three levels
A pillar frame, a two-tower fort and a stepped pyramid, each a function that returns bodies.
Stones and stars
A limited ammo supply, a 300-point bonus per unused stone and a three-star rating.
Hand-drawn scene
Bodies, band, fork, parallax hills and drifting clouds are painted in afterRender.
Clean-up and caps
Spent stones are removed and particles are capped so the world stays light.

Step by step

How to Use

  1. 1
    Press PlayA card explains the goal: pop every green critter before the stones run out. The stones left are shown as dots in the HUD.
  2. 2
    Drag the stone backPull it back from the sling, up to 130px. A dotted line shows the exact path the stone will take.
  3. 3
    ReleaseThe stone launches at a speed proportional to the pull. Pull further for more power and change the angle for a different arc.
  4. 4
    Use the materialsGlass shatters at a touch, wood holds, and stone is heavy. Knock out supports so the structure drops onto the critters.
  5. 5
    Clear the levelPop all critters to win, earning 500 each, 300 per unused stone, and up to three stars. Next level changes the structure.
  6. 6
    RetryRetry level resets the structure and restores the score from the start of that level.

Real-world uses

Common Use Cases

Complete mini-game
Start from a full game with levels, ammo, scoring and a results card, then reskin the critters, blocks and background for your own theme.
Teaching projectile motion
Because the dotted path replays the same gravity and drag the engine uses, students can see launch speed, angle and distance connected before they release.
Promotional microsites
Turn a campaign into a shareable game by swapping the critters for your mascot or product, and the results card for a discount or sign-up prompt.
Level design prototyping
Add a level as a function placing blocks relative to the platform, then test how materials and layout change the difficulty in seconds.
Learning Matter.js events
A compact reference for startdrag and enddrag, collisionStart with relative speed, custom rendering in afterRender and destination-over backgrounds.

Got questions?

Frequently Asked Questions

The launch velocity is set directly from the pull (distance times POWER), so the preview repeats Matter's own per-step update: multiply the velocity by one minus the air friction, add 0.2778 of gravity, then move. Plotting every fourth position until it reaches the ground gives a path that matches the real flight.

A spring's launch speed depends on stiffness, damping, mass and frame timing, which makes a trajectory impossible to predict exactly. Computing velocity from the pull gives predictable shots and an accurate preview, while the spring only holds the stone at rest.

Add an object to LEVELS with a stones count and a build function that returns bodies, using block(kind, dx, bottom, w, h) and critter(dx, bottom) to place things relative to the platform. The HUD, win check and star rating pick it up automatically.

In collisionStart the relative speed between the two bodies is measured. A critter pops above 3.6 against a moving body or 7.5 against the ground, and glass shatters above 4.2 or 6.5. Raise the numbers for sturdier objects.

Setting render.visible to false on each body and painting them in afterRender gives full control: faces on critters, grain on wood, cracks on stone and shine on glass. The polygon vertices from Matter are used for the shapes, so collisions and visuals stay in sync.

Copy & paste

Source Code

Requires
<div class="sl">
  <div class="sl-hud">
    <div><span>Level</span><b id="slLevel">1 / 3</b></div>
    <div><span>Critters</span><b id="slTargets">0</b></div>
    <div><span>Stones</span><i class="sl-stones" id="slStones"></i></div>
    <div><span>Score</span><b id="slScore">0</b></div>
    <div class="sl-btns"><button type="button" id="slRetry">Retry level</button></div>
  </div>
  <div class="sl-stage" id="slStage">
    <div class="sl-over" id="slOver">
      <strong id="slOverTitle">Slingshot Tower</strong>
      <div class="sl-stars" id="slStars" hidden></div>
      <span id="slOverText">Pop every green critter before you run out of stones. Drag the stone back, follow the dotted line, then let go.</span>
      <button type="button" id="slGo">Play</button>
    </div>
  </div>
  <p class="sl-hint">Pull back up to 130 px. The dotted line shows the exact path. Glass shatters, stone is heavy, wood is in between.</p>
</div>

Extend with AI

Take This Snippet Further With AI

Paste this game into an AI assistant like Claude and ask it to explain how POWER, GRAV and AIR make the dotted preview match the real flight, or how enddrag decides between launching and returning the stone. Since levels, materials, critters, stars and particles already exist, ask for what is missing: different ammo such as a splitting stone or a bomb, a level editor that saves layouts as JSON, a wind setting that the preview also respects, sound effects for launches and pops, a combo multiplier for chain reactions, or a mobile layout with a larger grab area around the stone.

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

Requirements:
- A ground, a static wooden platform on a post and a stone held at a fixed anchor by a weak spring constraint. Draw every body, the sling fork and the band by hand in afterRender (set render.visible = false on all bodies), with clouds, two hill layers and grass painted last using destination-over.
- Drag only the loaded stone (reject other bodies in startdrag), clamp the pull to 130 px from the anchor, and on enddrag with a pull of at least 28 px detach the spring and call Body.setVelocity with (anchor minus stone position) times 0.12. Spend one stone and load the next after 900 ms.
- While dragging, draw a dotted preview by replaying the engine's step: v = v * (1 - frictionAir) + gravity * 0.2778, position += v, dotted every fourth step until the ground.
- Materials: wood, stone (about 2.5x denser) and glass (lighter and fragile). Glass shatters into shards and gives 50 points when the relative impact speed in collisionStart is over 4.2 (6.5 against static bodies).
- Green critter targets (circles with blinking faces) pop when hit at relative speed over 3.6 (7.5 against the ground): 500 points, confetti and a short screen shake.
- Three levels defined as functions returning bodies placed relative to the platform: a pillar frame, a two-tower fort with glass and stone floors and a pyramid from Composites.pyramid with critters on the platform.
- HUD with level, critters left, stones as dots and score. A start card, a level-cleared card with 1 to 3 stars (3 stars with two or more stones left) and +300 per unused stone, and an out-of-stones card with Try again. Retry button restores the score from the start of the level.
- Remove stones that leave the scene or are older than nine seconds, and cap the particle count.

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.