Projects › Science & visuals › Gravity simulator

A free gravity simulator to play with online, and how to make your own

Throw planets, watch them orbit, crash worlds together and pull two galaxies apart. Everything follows Newton's real law of gravity, so every orbit and every crash happens on its own. Play with it free right here, then build your own gravity simulator with a free AI assistant, one stage at a time.

Medium 1 to 2 hours Free · nothing to install Nothing is uploaded
Scenes
Drag to throw a planet. Let go to launch it.
Throw a
Speed

Runs on your device and nothing is uploaded. Real Newtonian gravity, up to 300 bodies.

Watch it come together, start to finish
What you'll build

Your own gravity simulator, built in stages

A gravity simulator looks like serious science, but it all comes from one rule that fits on a postcard. That makes it a brilliant thing to build with AI: you describe the rule and how it should look in plain English, and the assistant writes the code. You won't write any yourself. You describe, paste, test and paste back any errors.

  • A gravity sandbox that opens in any web browser, works offline and runs smoothly on a laptop or phone
  • Stars, planets and moons that all pull on each other with Newton's real law of gravity
  • Drag to throw, with a dotted line that shows where your planet will go before you let go
  • Crashes that merge two bodies into one with a flash, keeping all the mass
  • Glowing trails that draw the shape of every orbit
  • Five scenes: a solar system, binary stars, the famous figure-eight, a planet smash and a galaxy collision

Good for: space fans, children learning about orbits with a parent, teachers who want a live demo of Newton's gravity, and anyone who's built one of our games and wants to try some real physics.

Before you start

What you need

An AI chat assistantClaude, ChatGPT or Gemini. The free versions work for the first steps. This becomes a fairly long file, so for steps 4 to 6 pick your assistant's most capable model if you're given a choice. Smaller, faster models are more likely to cut a long file off or break something that was working. If a free plan hits its daily limit, carry on tomorrow with the copy you saved.
A text editorNotepad or TextEdit (in plain text mode) works. The free VS Code makes long files easier to handle.
A web browserAny up-to-date browser on a computer, tablet or phone. Nothing to install and no account needed.
New to saving files like this? Read How to save and open an HTML file first. It takes two minutes. Most AI assistants are for adults or teens, so if you're building this with a child, do the chatting yourself and let them do the testing.
Before you start

The trick to bigger builds

Big projects go wrong when you ask for everything at once. So this guide builds the simulator in stages. After each stage, play with it, check it works and save a copy (gravity-v1.html, gravity-v2.html and so on). If a change goes badly, open the last good copy, paste it back into the chat and say "Let's go back to this version."

The idea behind it is called an N-body simulation: a list of bodies that all pull on each other, moved forward in tiny steps. AI assistants know it well. Famous examples to look at for inspiration are Universe Sandbox and PhET's free My Solar System.

Step by step

Build it in six steps

Step 1 gives you a simple version that works, and each step after it adds more. The simulator at the top of this page is roughly what you'll have once you've done every step. Yours will look a bit different, because the AI writes its own version each time.

  1. Start with planets going round a star

    The first version is a star with a few planets circling it. It's small, but it already uses the same law of gravity that space agencies use to plan missions.

    Copy this prompt
    I don't know how to code. Please make me a gravity simulator that runs in a web browser.
    
    Requirements:
    - Everything in ONE single HTML file (HTML, CSS and JavaScript together), so I can save it and double-click it. No external libraries and no internet connection.
    - A wide canvas with a dark space background and a scattering of faint stars. Make it sharp on high-resolution screens by using devicePixelRatio.
    - A list of bodies, each with a position, a velocity and a mass. Draw each one as a glowing ball whose size grows gently with its mass.
    - Start with one heavy star in the middle and five planets at different distances. Give each planet exactly the sideways speed it needs for a circular orbit: speed = square root of (G x star mass / distance).
    - Every body pulls on every other body using Newton's law of gravity: force = G x mass1 x mass2 / distance squared.
    - Move everything with the "leapfrog" (velocity Verlet) method, in several small fixed steps every frame, so orbits stay steady instead of spiralling in or out.
    - Add a little "softening" so two bodies that get very close don't get a huge, sudden kick.
    - Pick G and the masses so the inner planet goes round in about 4 seconds.
    - Run it with requestAnimationFrame.
    
    Please give me the complete file in one code block, then tell me in simple steps how to save and open it.

    Save it as gravity.html and double-click it. You should see the planets circling the star, the inner ones faster than the outer ones, just like the real solar system.

    Nothing happens? Press F12 (or Cmd+Option+I on a Mac), click the Console tab, copy any red text and paste it into the chat. The AI fixes most errors straight away once it can see the message.
  2. Drag to throw a planet, with a path preview

    Now you get to join in. Press where the new planet should start, drag the way you want it to go, and let go. A dotted line shows where it will travel before you let go, so you can aim.

    Copy this prompt
    That works, thank you! Now let me throw in my own planets:
    - Press on the canvas to choose where the new planet starts. Drag away from that point in the direction I want to throw it, and let go to launch it. The longer the drag, the faster it goes.
    - While I'm dragging, show the planet waiting at the start point, a dotted line from it to my finger with a little arrowhead, and a dotted predicted path showing where it will go. Work out the path with the same gravity and leapfrog maths as the real thing, a few seconds ahead, using the six heaviest bodies so it stays quick. Update it every frame as I move.
    - If the path hits something, mark that spot with a small starburst.
    - A tap without dragging should pop the planet into a neat circular orbit around whatever is pulling on it most.
    - Use pointer events so it works with a mouse, a pen or a finger.
    - Put a hint on the canvas: "Drag to throw a planet. Let go to launch it." Hide it after my first throw.
    - Under the canvas, five buttons to choose what I throw: Moon, Small planet, Planet, Giant planet and Star, each much heavier than the one before, with the selected one highlighted. The hint should name the one I picked.
    
    Send me the whole updated file, not just the changed parts.
    Always ask for the whole file. Then you replace everything, save, and refresh the browser tab (F5, or Cmd+R on a Mac).
  3. Crashes that merge

    When two bodies touch, they join into one bigger body with a flash. The total mass and the total push (momentum) stay exactly the same, just as they do in real collisions in space.

    Copy this prompt
    Please add collisions:
    - When two bodies touch (the distance between their centres is less than their two radii added together), merge them into one.
    - The new body's mass is the two masses added together. Put it at their centre of mass, and give it the velocity that keeps the total momentum the same: add up mass x velocity for both, then divide by the new mass.
    - Keep the heavier body's colour. If the merged body is heavy enough, turn it into a star.
    - Make the moment satisfying: a bright flash that grows and fades, a ring that spreads out, and a burst of sparks. Bigger crashes get bigger flashes.
    - Check for collisions after every small physics step, not just once per frame, so fast bodies can't pass straight through each other.
    - Show a small counter in the corner with how many bodies there are and how many crashes have happened.
    - Add Pause/Play and Clear buttons. Clear removes everything except one star in the middle, so there's always something to throw at.
    - Let planets catch moons. If something much lighter than a planet drifts close to it (bigger planets reach further), gently nudge its speed, relative to the planet, towards a neat circular orbit round the planet over about a second. Give the planet the opposite nudge so the total momentum stays the same. Leave fast fly-bys alone so they swing past instead.
    
    Send me the complete updated file.
  4. Trails and glow

    Trails are what make a gravity simulator beautiful. Each body leaves a fading line behind it, so you can see the shape of every orbit.

    Copy this prompt
    Please make it look beautiful:
    - Give each body a trail: remember its last 90 positions in a small ring buffer and draw them as a line in the body's colour that fades out towards the tail. Store the trail in space coordinates, not screen pixels.
    - Draw the trails and glows with the "lighter" blend mode, so overlapping light adds up and glows.
    - Stars: a white-hot centre with a big soft yellow glow. Planets: a shaded ball, lighter on one side, with a small glow. Moons: small and pale.
    - Draw the glows from small ready-made images (an offscreen canvas for each colour) instead of making a new gradient every frame, so it stays fast.
    - Add a "Trails" tick box to turn the trails on and off.
    - If a body goes off the edge of the screen, show a little arrow on the edge pointing to where it is.
    - Keep the view centred on the centre of mass of everything, gliding smoothly, so a drifting system doesn't wander off screen.
    
    Send me the complete updated file.
    Something stopped working? Tell the AI exactly what you did and what happened, for example: "When I throw a moon, the dotted line points the wrong way. It used to work." That's usually all it needs.
  5. Ready-made scenes and speed

    Scenes are the quickest way to see how strange and lovely gravity can be. Each one sets up a famous situation in one click.

    Copy this prompt
    Please add a row of scene buttons above the canvas. Each one clears space and sets up a new situation, with a one-line message saying what's happening:
    - Solar system: one star, four planets spaced well apart (one big planet with its own moon), a ring of small asteroids, and a comet on a stretched orbit. Load this one when the page opens.
    - Binary stars: two stars of different masses circling their shared centre, with two planets orbiting far out around both.
    - Figure-eight: three equal stars chasing each other round a figure-of-eight path. Use the famous starting positions and speeds found by Chenciner and Montgomery, scaled up to fit the screen.
    - Planet smash: pairs of planets on the same orbit going opposite ways, so they crash head-on, plus some moons on messy orbits.
    - Galaxy collision: two swirling discs of about 110 tiny stars, each round a heavy, compact centre, swinging past each other so long tails get pulled out. The tiny stars shouldn't crash into each other (in real galaxies they almost never do).
    
    Then:
    - Run each scene a second or so ahead before showing it, so the trails are already drawn.
    - Add speed buttons: Slow, Normal, Fast and Turbo (half, 1, 2 and 4 times). Keep the physics step the same size and just do more steps per frame.
    - Add a "Merge when they crash" tick box. When it's off, bodies pass through each other instead.
    
    Send me the complete updated file.
  6. Make it solid on phones and laptops

    The last step makes it feel finished, and stops it ever freezing however many planets you throw in.

    Copy this prompt
    Please finish it off:
    - Never let more than 300 bodies exist. If I try to throw more, show a friendly message instead.
    - Limit how much work it does each frame: if there are lots of bodies, do fewer steps and let time run a little slower rather than freezing.
    - Remove any body that flies a long way off screen, and show how many "flew off" in the corner counter. Also remove anything whose position stops being a real number.
    - Phones: drag to throw with one finger, and never scroll the page while I'm touching the canvas (touch-action: none, and preventDefault on touch events). A second finger cancels the throw. Make the canvas taller than it is wide on narrow screens, and make sure nothing on the page scrolls sideways.
    - Use devicePixelRatio (up to 2) so it's crisp on every screen, and resize properly when the window changes.
    - Stop the animation when the simulator is scrolled out of view or the tab is hidden, to save the battery.
    - Keep it running even if my computer has "reduce motion" turned on. The motion is the whole point.
    
    Send me the complete updated file.
ADVERTISEMENT · IN-ARTICLE
If it goes wrong

Quick fixes

The planets spiral into the star or slowly drift away

The AI has probably used the simplest way of moving things (called Euler), which slowly adds or loses energy. Ask: "Please use leapfrog (velocity Verlet) integration with a small fixed time step and several steps per frame, not simple Euler."

Two bodies get close and one shoots off at a crazy speed

Gravity gets enormous when the distance gets tiny. Ask for "softening, so the pull eases off when two bodies overlap, and check for collisions after every small step".

My planet doesn't follow the dotted line

The preview is being worked out differently from the real thing. Ask: "Make the predicted path use exactly the same gravity and leapfrog code as the simulation, starting from the same position and speed the planet will be launched with."

It gets slow with lots of planets

Ask:

Copy this prompt
The simulator gets slow when there are lots of bodies. Please make it faster: cap it at 300 bodies, work out each pair of bodies only once (the pull on one is the exact opposite of the pull on the other), draw the glows from ready-made images instead of new gradients, draw shorter trails for tiny bodies, and limit the number of physics steps per frame so time runs slower instead of the page freezing. Send me the complete fixed file.
Everything drifts off the edge of the screen

The whole system is moving, which is real physics, but annoying. Ask the AI to "keep the view centred on the centre of mass, gliding smoothly, and add the centre's speed to anything I throw".

The page scrolls when I drag on my phone

Ask the AI to "set touch-action: none on the canvas and call preventDefault on touch events while I'm throwing".

The page is blank

The AI's reply was probably cut off. Scroll to the bottom of its code: it should end with </html>. If not, ask: "Your code was cut off. Please send the complete file again."

Questions

Questions people ask

How do I use this gravity simulator?

Press anywhere in space, drag in the direction you want to throw, and let go. The dotted line shows where your planet will go before you let go. Choose a moon, a small, medium or giant planet, or a star underneath to change what you throw. Bigger planets pull harder and catch passing moons from further away. Or tap a scene like Planet smash or Galaxy collision to see what gravity can do.

Is this gravity simulator free to use online?

Yes. It's free, it runs in your web browser on a computer, tablet or phone, and there's nothing to download or sign up for. It all runs on your device and nothing is uploaded.

What is a gravity sandbox or orbit simulator?

It's a toy universe: you add stars, planets and moons, and the computer works out how gravity pulls them. Nothing is scripted. Every orbit, near miss and crash comes from one simple rule, worked out hundreds of times a second.

Is the physics simulation realistic?

It uses Newton's law of gravity, the same maths used to plan space missions, and a careful method called leapfrog that keeps orbits steady. To keep it fun and fast it's flat (2D), the sizes and distances aren't to scale, and bodies merge when they touch instead of breaking into pieces.

Why do my planets crash into the star or fly away?

It's all about sideways speed. Too slow and gravity wins, so the planet falls in. Too fast and it escapes. In between, it orbits. Watch the dotted path while you drag and adjust until it loops round. A quick tap pops a planet straight into a neat orbit.

Does it work on a phone or tablet?

Yes. Drag with one finger to throw, and the page won't scroll while your finger is on the space. Put a second finger down to cancel a throw.

Make it your own

Twist it into something else

Once your gravity engine works, you can turn it into all sorts of things:

Slingshot space game

Launch a little spaceship and use a planet's pull to swing round it and reach a target. Add a fuel gauge and a set of levels.

The real solar system

Use the real masses and distances of the Sun and planets, with a speed in days per second, and compare a year on Earth with a year on Neptune.

Black hole

A body that swallows anything that comes too close, with a glowing ring of matter spiralling into it.

Orbit music

Give each planet a note that plays every time it passes the top of its orbit, so a solar system becomes a slow, looping tune.

Made something amazing? Send it to us. We feature reader projects.

Why it works

Why planets go round instead of falling in

In 1687 Isaac Newton wrote down one rule: everything pulls on everything else. Heavier things pull harder, and the pull gets weaker quickly as things move apart. Twice as far away means only a quarter of the pull.

So why doesn't a planet just fall into its star? Because it's also moving sideways, very fast. Imagine throwing a ball so hard that by the time it has dropped a little, the ground has curved away beneath it. It keeps falling and keeps missing. That endless falling and missing is an orbit. Too slow and it falls in, too fast and it escapes, and just right it loops round for ever.

The simulator just applies Newton's rule over and over. Hundreds of times a second it works out the pull between every pair of bodies, nudges their speeds, then moves them a tiny bit. The leapfrog method does this in a careful order (half a nudge, a move, then another half nudge), which is why the orbits stay steady instead of slowly spiralling. When two bodies touch they merge: their masses add up and their combined push stays the same, so nothing is created or lost.

Building one is a lovely way to see that a few lines of maths can make something that feels alive. It also teaches the habit that matters most with AI: describe the rule clearly, test it, and adjust.

Keep going

What to build next