Hacker News new | past | comments | ask | show | jobs | submit login
Gravity Simulator (nowykurier.com)
467 points by evanb on Sept 8, 2014 | hide | past | web | favorite | 131 comments

I did something similar, but with combat - ships, lasers and missiles.

There are a couple of variations, and some tweaks like the ships accelerating perpendicular to the planets so they don't crash land.




I have a non-combat version in 3d. Now I know what mine is missing. https://www.youtube.com/watch?v=73O8aDN41sU

Very cool. I notice that many ships tend to get stuck on the edge of the map though. Maybe make it so they loop back around to the other side of the map?

Thanks. Yeah, there are a couple of glitches in there. The ships bounce off the edge of the screen, and smaller ships run from bigger ones -- combined, that makes them crawl along the sides. Looping around is a good idea, or I'm wondering if there could be some kind of log scale to distance the further out from the centre the ships get. I did a variation a while back with a star in the middle that could be tweaked for that (click to add a ship). Mind you, the gravity from the star pretty much takes care of that problem.


> Maybe make it so they loop back

That's be a toroidal spacetime surface, wouldn't it? Would gravitational influence also have to "loop around" the borders?

If not, you might get some very interesting effects if a mass is near the edge of the map.

That was great. COngrats!

That is really cool.

It's really nice. Be sure to activate paths, I'm having a lot of fun using that to draw cool stuff :).


That was me trying to have a small particle making an 8-shaped path around two bigger ones that would be sufficiently far apart to not interact too strongly with each other. Of course, when the small particle went between the two bigger ones, it shifted their position a tiny bit, but sufficiently for those two to start very slowly moving towards each other, while the small particle was headed straight to the up-right direction. But when the two bigger particles became close enough to finally meet and become one single huge particle, it attracted back the small one, which since then goes back slowly to the huge particle only to shift it a bit and be "relaunched" by it for a new lap. The system seems to be totally stable that way.

Update: https://i.imgur.com/heHekdc.png

> That was me trying to have a small particle making an 8-shaped path around two bigger ones that would be sufficiently far apart to not interact too strongly with each other.

This kind of path is called a free return trajectory and was used in the Apollo program lunar missions. The trajectory is not periodic, ie. it doesn't repeat more than once. The trajectory around the earth takes less time than lunar period ("month") so when the craft goes back up, the moon has moved on. You might be able to construct a planet-moon system with an m:n resonance in the orbital periods of the moon and the craft so that the tracjetory is periodic.

Free return trajectories are used in manned space flight to guarantee that the craft and crew return to earth if a failure prevents from entering lunar orbit.

Quote: "Particle mass is log of radius". Why not use real physics and make the mass proportional to the cube of the radius? It's also easier to compute. In fact, taking the log of the radius goes in the wrong direction -- the mass of a planet really does increase as the cube of its radius, which changes in a way opposite to log().

Oh, well. Here's my gravity simulator -- it uses JavaScript, no flash required:


> "Particle mass is log of radius"

They seem to have corrected the sentence now: "particle radius is log of mass".

Wow, your simulator is much nicer, plus a great article about it to boot! You should add an option to play cosmic billiard, that's probably the main appeal of the flash simulator :)

Thanks for your kind comments!

> They seem to have corrected the sentence now: "particle radius is log of mass".

It's still wrong. Here's a graph comparing mass = e^radius (the reciprocal of radius = log(mass) ) versus mass = radius^3:


My point is that the two functions have a different behavior, the absolute values generated aren't very important compared to that. For solutions to f = G m1 m2 / r^2 where both bodies are computed, this will produce results wildly different than reality. (If only one body is computed, for example against a much larger parent body mass, the satellite mass stops making a difference.)

> You should add an option to play cosmic billiard, that's probably the main appeal of the flash simulator :)

Nice idea. I was more interested in portraying the solar system using real planetary masses and real physical constants. Still, it's a nice suggestion.

Very cool! I was able to get 2 masses to oscillate around each other in a funny way[1]. Seems they keep going like that forever. What is this kind of equilibrium called?


Isn't that a normal orbit around a common centre of mass? As the objects have a similar size the centre of mass appears to wobble as it moves along. In the frame of the centre of mass, the objects would just go round in standard orbits.


That's the thing with those kind of simulators (or, actually, with reality), your reference has no relation to the center of mass of the system.

Of course, if you "were there" the reference would be the center of mass, like the reference of the solar system is "The Sun" (or a point inside it)

The center of mass of the solar system isn't always within the Sun.


> Isn't that a normal orbit around a common centre of mass?

If you limit yourself to looking at the position of one body with respect to another, the orbit will be an ellipse. A circular orbit is simply a special-case ellipse with an eccentricity of zero. This is true for any two orbiting masses -- from the perspective of either of them, the other body's orbit will be an ellipse. And yes, it's always with respect to the common center of mass.

Interestingly, mostly because of Jupiter, the solar system's common center of mass can sometimes lie outside the sun.

Once you change references frames to the center of mass, two bodies that are gravitationally bound are always following ellipses. It looks like this in the case where they have equal mass:


Likewise, two bodies that are not bound will follow hyperbolas in the center of mass frame.

> Likewise, two bodies that are not bound will follow hyperbolas

Or parabolas, which also represent unbound solutions. In an orbital system, a parabolic trajectory represents escape velocity (exactly), a solution in which the escaping body's velocity is in progressive decline, and that reaches zero at infinity.

Looks like a binary star, similar to the two suns of Tatooine.


OP: This is an amazing tool to learn the sensitivity of dynamical systems to initial conditions. Well done!

I've been playing with it too: http://imgur.com/VAHTfg9

It took a little bit to generate this one.

If they were truly rotating around each other in a repeatable way, it would be a harmonic oscillator.

An orbit :)

If you're interested in learning some of the basics behind this kind of simulation I highly recommend the Nature of Code by Daniel Shiffman - lots of physics and programming fun.


This is nice, but please rename the OMFG button. As someone who works in K-12, it would be a shame if a program like this is rejected because of a button.

As someone who works in K-12, allow me to familiarize you with the "Oh My Freaking Goodness!" initialism.

agreed. This is really cool (and simple too)

Also, how hard would it be to set an initial state of our current solar system? Teachers could set up scenarios for students to interact with, and allow students to collaborate.

Maybe as simple as an output/input of textual data for saving & restoring state? i'd love to try model our current solar system, and see if i can get something to mars with just an initial trajectory.



The scale of the Solar System would require you to visualize the bodies as much larger than their true size in order to see everything on one screen. If the Sun is 1 pixel, all other bodies are way smaller than a pixel, and Neptune is 3000 pixels away. And of course, you'd probably want to speed up the simulation speed.

Maybe I should clarify that I didn't make this, I just stumbled upon it and thought other people would also get a kick out of playing with it :)

There exists a similar if not more robust gravity simulator that's available for free to schools. It's called Universe Sandbox. Here is a link for instructions on obtaining educational licenses. http://universesandbox.com/blog/category/education/

Just out of curiosity (I'm not offended by OMFG myself), I'm wondering: would "ZOMG" be ok?

Its a shame that a simple button label would be the cause of an education tool to be rejected... sissy-state for the win!

OMFG is not a standard abbreviation. If you are making a tool that can be used worldwide, best to stick with words and slangs that are universally known.

Moreso, best to stick with terms that are acceptable to people of all cultures and backgrounds. The word 'fucking' may be a light-hearted slang to a 20 year old american, but it may just be offensive to someone older living in the UAE.

Professionalism, though not perfect, does in fact help in making people from various background agree and understand good ideas by being austere, simple and well-defined.

Even with the USA "fucking" would be unprofessional!

Very nice, wish it was HTML5 rather then flash.. It brings to light how hard it is to get a stable solar system. And of course I knew this but playing around I realized our sun is not stationary either... It's easy to forget the entire solar system we live in is this amazing mix of interactions between the planets, sun, other debris and outside mass from other parts of the universe.

Can someone explain the math behind this? Which methods were used? I wasn't aware it was possible to run such a simulation on flash because each body results in 6x more calculation. Is this like plugging in the masses into a single equation? I want to learn more about how this is done .

The simplest numerical approximation method is Euler's method. It also tends to be unstable.

Personally I prefer to just throw a fourth order Runge–Kutta (RK4) at things and normally that's more than good enough.

List of reading:







> Personally I prefer to just throw a fourth order Runge–Kutta (RK4) at things and normally that's more than good enough.

In the context of gravity simulation, I must point out that while Runge-Kutta/RK4 is good enough for a lot of stuff but it has a tendency to dissipate energy. It's not very good in a simulation where the conservation of energy is important. Run a simulation long enough and the orbits will eventually shrink.

If scientific accuracy is required, gravity simulations are usually done with "symplectic" integrators (which don't "lose" energy) and the equations of motion are written using Hamiltonian mechanics. There are symplectic variants of Runge-Kutta too.

In an exercise work for a celestial mechanics course, I wrote an n-body simulator using a dissipative Runge-Kutta method (because it was good enough for that, and the exercise was about using RK methods). Simulating an exoplanet system (HR 8799), the orbits were stable and 100 year simulation gave near perfect orbits. After 1000 years, there orbits were a bit smaller and after 10000 years, they had lost a fourth of the initial energy. This was done using one day timesteps.


> Can someone explain the math behind this? Which methods were used?

I can't speak to the linked simulator, but gravitational calculations are relatively simple -- they represent the solution to a numerical differential equation that, in small slices of time, solves:

f = G m1 m2 / r^2


f = force, Newtons

G = Universal gravitational constant: http://en.wikipedia.org/wiki/Gravitational_constant

m1 = mass of body 1, kilograms

m2 = mass of body 2, kilograms

r = distance between m1 and m2, meters

Here's my simulator, plus (further down the page) a complete description of the math. My simulator uses HTML5 and JavaScript:


> I wasn't aware it was possible to run such a simulation on flash because each body results in 6x more calculation.

It's more accurate to say that the total computing time required changes as the square of the number of modeled bodies. That's worse than 6x, by the way, for a sufficient number of bodies. One solution is to use a large central mass and only compute the paths of some satellites with respect to the central mass, not with respect to each other.

The calculations that impress me (and I do a lot of this kind of math) are the cosmological modeling of galactic clusters of hundreds of thousands of stars, all interacting with each other, with no central mass to stabilize things. This requires a supercomputer and many hours of online time.

> Is this like plugging in the masses into a single equation?

No, because for more than two bodies, there's no closed-form solution (this is called the "three-body problem"). Solutions must be arrived at numerically. When NASA wants to compute where to land a spacecraft on Mars, they have to use numerical methods -- very good ones, but numerical methods.


Here are the people who do this for NASA planetary missions:


Here's a snapshot of object locations in the inner solar system:


There are a lot of challenging problem areas: rendezvous with small bodies (very irregular gravity fields), mission trajectory design, operations planning for flybys in the presence of, say, camera pointing constraints.

(@lutusp knows this already -- I'm putting it here just for interest.)

Great job! Took a while to figure out for panning I just have to move and not click. Looking at the source always helps ;)

Right-clicking is a nice treat! Interesting to compare the different integration methods, too. Excellent work.

It would be nice to arbitrarily choose a specific particle to be the center of the system (the frame of reference).

The source is browsable if you modofy the URL. I expect someone with create a canvas driven clone within 48h:)

Great! I tried it out; when I combined a galaxy with a field , many particles went flying from the center at a high rate of speed. Why is that?

When a small particle gets accelerated to great speeds as it approaches a massive object it simply passes through because the collisions are off/aren't perfect even when they're on

Reminds me of orbitalis - a Ludum dare game from last year that eventually ended up on steam. Object is simple, establish a stable orbit in the system for a span of one clock rotation (clock is on the very outside.) See http://www.alanzucconi.com/extra/0rbitalis/ld48/

I once wrote a similar simulation in C: https://github.com/kgabis/gravitysim It uses Barnes-Hut algorithm, so it runs in nlogn, instead of n^2.

I did something similar in Javascript. My implementation uses the Runge-Kutta algorithm, that is more stable. My GUI does not allow planet creation, but it shows several stable configurations, including the 13 recently found three body planar orbit configurations.

http://jbochi.github.io/planets/ http://suki.ipb.ac.rs/3body/

Love this. I managed to get a pretty stable orbit by using the right angle and velocity (by chance). Highlighted in yellow: http://i.imgur.com/OOaTLMP.png

This is the coolest trajectory found on this thread for now!!!!

It ran for several hours like that and never deviated from the original "circular" path. Unlike the other attempts, which were all much more elliptical. I guess that's kind of how planets would stay in a stable orbit though, having the right distance and speed for their mass.

I, like many others on this thread, have dabbled in the Gravity Simulation game. I've done two of them.

The first one was back in 1999, I wrote one with 13h[1] graphics for DOS (Borland Turbo C++), and to make it more fun, I used flat sprites to represent the objects (so the objects progressed from being rocks to asteroids to planets - with the largest sprite I used being an image of Jupiter).

A few years later, I rewrote it in OpenGL (using the GLUT library) for a class. It worked much better (and of course the hardware was much faster too).

I had always planned rewriting the physics engine to use Barnes-Hut, but never got around to it, so it always ran at N^2.

Anyway, for the curious, the code is up on Github amongst my collection of other old garbage stuff from back in the day: https://github.com/choptastic/OldCode-Public/tree/master/Gra...

[1] http://en.wikipedia.org/wiki/Mode_13h

Here is Universe Sandbox, a gravity simulation that can do massive scale simulation on home computers. Neat demo videos about colliding galaxies, etc.


Can anyone explain the graphical effects that appears here in the white lines https://i.imgur.com/sRCLAsn.png https://i.imgur.com/81Jf56H.png?

(To reproduce, use a really big stable mass (either enter it by hand or use the OMFG button and click several time at the same position without moving your mouse) and launch at fast speed a tiny particle in an approximately tangent direction of a circle centered on the big mass.)

That's a Moiré pattern and is an interaction of the resolution of your display and the proximity of the lines.


That was quick! Thanks!

I didn't know that Moiré pattern could appear on a screen "without" a second grid (or rather, I didn't realize that the pixels of my display could serve as the second grid, which is kind of obvious now that you said it).

New screenshots: https://imgur.com/a/7W9FI :)

Relevant: http://codingmath.com/ Really nice series, showing how to do vectors, gravity and so on in JS.

Ok, maybe I should finally buy Kerbal Space Programme

Built something similar in C/GL a few years back. Quite a fun exercise, it only took a couple of hours to get the basics working. It has no collision detection, so particles that end up too close end up with infinite velocity, which is quite fun to watch.

EDIT: oh hey, I found a binary. https://www.dropbox.com/s/ihfqnzjaxhtskwt/Screenshot%202014-...


Can I play? I wrote a RK4 gravity simulator a while back in WebGL, but my main goal at the time was to find a way to visualize gravitational fields, so its nowhere near as interactive or user friendly as your implementation.

I was trying for the effect you see in high school physics videos. My approach was to use a plane geometry mesh and apply a vertex displacement shader, but never quite got it to look or perform how I wanted.


Wow this is fun. But it has so much potential for improvements!

  -Saving your setting
  -Auto generate small object in perfect circle orbit around larger object, and generate sun-earth-moon system
  -Export setting to other people
  -Allow to numerically finetune locations and velocities
  -Don't ruin the trails when dragging
  -Make it run faster, especially with trails enabled
  -etc... :)
EDIT: Gee, when will Hacker News finally support newlines properly?

I would like to name individual "bodies," the ability to zoom in and out, and maybe even a mathematical readout of some sort. The values behind trajectory, etc.

well at least it supports negative mass ;)

I've made touch interactive installation at 2008 with similar physics simulation http://vimeo.com/19361057

Such an amazing simulator to play with. I can only imagine how breath-taking this can be for kids to play around, plus it teaches physics!

Think about how breath-taking and educating must it be for a kid to write such a thing.

As a person who actually learned basic mechanics by writing video games I do believe that "you ain't understood nothing until you know how to teach it to a computer". Trying to express knowledge in (working) code is a great exercise that mercilessly catches even tiny holes in one's understanding.

Ditto that, I often tell people computers are very stupid. One proof of that is they let humans program them. The second proof is you have to teach them everything from scratch. :-)

I have a question about a phenomenon I am seeing.

say you add 3+ equal mass objects without a velocity and they all collide with each other without "missing or orbiting" one another. Sometimes the final mass will have a velocity.

It would seem like it should not have a velocity because it would be canceled out. What am I missing? Where is this energy coming from?

In real life, the three colliding bodies would convert their kinetic energy into heat and combine into a very hot body. Sort of how we think the moon was created, from a Mars-sized body colliding with Earth long ago.

But in a numerical simulation, usually what happens is that three bodies on a collision source approach one another but, because of the limitations of numerical differential equation solving, suddenly fly away from each other in a rather non-physical way, and with more energy than they had to begin with.

The tl;dr: most of the funny effects in a simulator arise from the limitations of numerical simulation methods, and many of those aren't representative of real physics.

Hey.. TBH its real fun to play with it.

Question.. How big is the frame? I create two objects and they went out of frame. Then I create 2 more but a bit bigger ones and after 2-3 minutes I see those two objects coming back and it looks good too :D .. check it out http://imgur.com/IBYeysm

I don't think there is a "frame". It solves for all particles all the time.

After all, if a particle leaves the viewport, it doesn't affect the particle count readout at all.

I assume if things move far enough, there would probably be interesting floating-point precision errors, but I'd imagine that would take quite a while.

The frame extends far beyond your the preset view. You can pan around with Control-click-drag.

I think I just learnt something about gravity and oscillations: http://i.imgur.com/OrUUFj7.png

Using the rapid-click feature on my mouse to place a dense circle outline: http://i.imgur.com/14IN5pi.png

And I think I just learned something about all of your open tabs and bookmarks

Hope it's useful :)

For historical interest: Here's a description of the humble beginnings of gravity put onto a computer's screen (think of PDP-1 Spacewar! code, 1962):


Cool, it's a good way to teach people about gravity. Most people don't know the basic idea of how falling and orbiting are connected. I once made a simple 'game' for this purpose:


really? i do remember the wow moment when i worked it out for myself but i was pretty young...

I did something similar on 3d but is not on realtime and generate outputfiles that could be ploted with gnuplot. It uses an third order Euler integration. Some day I should write a realtime mode for it:


This is pretty cool! I wonder if there's a way I could implement that somehow into our turtle graphics app. Turtle gravity?

As for this app it would be awesome if you could zoom out -- I find most of my stable(-ish) orbits are very long and at very large mass sizes, so it would be good to see their entire orbits.

did the same thing with box2d and sfml. not very hard to do...

a funny thing to do is to try to put those into a stable orbit

Does anyone know why perihelion moves in this simulation? I learned that perihelion movement can only be explained by general relativity, not newtonian mechanics. Is this just a limit of computer simulation? (which can't calculate the exact value of Gm1m2/r^2)

It is a shortcoming of the integrator (Euler), not in the calculation of the force (as you suspected).

See [1]. Especially slides 11 and 12 may be of interest.

[1] http://www.astro.sunysb.edu/phy277/lect30.pdf

As a sidenote, there are better integration schemes, but all of them will have some error because we discretize the system.

Wow that is really interesting. Thanks. By the way, if there are always some error in all systems, then what kind of systems are used by NASA or other space exploration institutes?

I'm not in the business of space mission engineering, so I don't know details. Sorry.

But in general, you can control the error and make a trade-off between computing time and accuracy. You would select a timescale over which you want the error to be below some value, and then only consider the simulation valid until then.

I would love to know if there's a name to this particular type of orbit, I spent a little bit too much time creating it and now need to know some more about it! :-) Anybody know how I can find out?



Would love a setting to select the number of objects to drop on click, and the spread for them ie (20 objects, 50px radius) and also for objects to gain the mass of objects that hit them, so that if a bunch of huge objects collide, they create a super-object

> for objects to gain the mass of objects that hit them, so that if a bunch of huge objects collide, they create a super-object

That's already what happens here.

I made this in CUDA a while back. Fun project - the naive n^2 algorithm is embarrassingly parallel so it's easy to write. Fun to hit the CPU/GPU switch and watch the huge performance boost, even on a dinky laptop GPU.

Be sure to click on the "Generate proto disk" button for instant action. :)

> Particle radius is log of mass.

Wouldn't it make more sense for the radius to be the cube root of mass (assuming uniform density)?

This makes it easy to understand why there are so many binary systems.

A friend of mine made something similar to this for iOS a while ago: http://gravityapp.info

His app is being used in schools.

Very fascinating! It reminds me of Conway's Game of Life, looking for different kinds of patterns that will make a stable construct and do something interesting.

At first I thought it was a 2D simulation but my attempt showed otherwise.


Really nice tool.

I think what you see there is not necessarily an indication of the simulation happening in 3-d space[1]. It is however evidence of [precession](http://en.wikipedia.org/wiki/Precession), which should not happen in a 2-body problem. If no other heavy body was close to the ones shown in your screenshot, this should actually not happen. Since the simulation does, however, only have a finite precision, this could very well be an artifact of the simulation (happens often if you have near-collisions, since the change of velocity there happens rapidly and is hard to describe correctly with a fixed-length time step).

[1] In fact if all initial positions and velocities lie in the same 2d plane, all trajectories would also lie in this plane. Since the interface only allows one to set such initial conditions, I am fairly confident that the simulation is 2d only.

Similar simulation I've made earlier:


Pure Javascript using Sylvester.js for Math.

Great! I wanted to say that the "add random" button tends to shoot particles light-years away, never to be seen again. Is that what you were intending?

It's pretty sweet I got this to happen http://i.imgur.com/Sk4Rznu.png

Somehow I ended up with a perfect orbit within my madness.


Why Euler? Isn't that terribly unstable?

Only in low FPS scenarios (it becomes even worse if the FPS is low AND wildly varies). For a toy like this there is nothing wrong with using Euler.

i like how the points merge, thats what makes this more than just a dumbass simulator imo. :)

took a while for me to work out though.

So cool. The amount of time I just spent playing with that is going to screw up my whole day tomorrow!!

I love this but its a pity that paths vanish when I click-drag the frame.

When I saw the mass OMFG I was expecting a black hole to pop up :(

I think the simulation of the real gravity is better. Because we can find out what is the hidden magic of nature. Then there comes accuracy issue of the simulation. How to tell us that your simulation will be `correct`?

What's it built in? Is code available? Cool demo!

It's telling me to install Flash, so I'd say, Flash?

confirmed - right click -> About Adobe Flash Player

this is awesome. had a look into doing this on the GPU a while ago, barnes-hut was the best speedup I could find

There has to be a game in this somewhere...

Check NVIDIA papers of doing "n bodies problem" on CUDA. They got awesome results.

Most awesome thing ever seen on HackerNews !!!

I'm stuck with an empty loading bar and

> Error #2046

This problem can be fixed by either increasing the Adobe Flash local storage space, (also known as “Flash cookies”) or deleting them.

How does one do that...?

I did "rm -rf ~/.macromedia/Flash_Player/" but still get Error #2046....

here is an interesting one


NSFW warning!!

It is not easy to draw a circle.

Next step: add dark matter

My simulator models dark energy (dark matter might be very difficult to model, since we don't understand it):


create a few random fields

turn on combine mass on collision

add galaxy in middle

watch the creation of a solar system :)

All of a sudden, the universe makes a helluva lot more sense now.

It doesn't work with Mozilla Shumway.

I reported the issue through Shumway UI, but I can file a separate bug.

> To view this page ensure that Adobe Flash Player version 10.0.0 or greater is installed.

What do you need Flash for?

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact