Friday, 5 September 2008

Physics + Programming = Pretty

Whilst looking for a better-than-mine Python implementation of attractive-and-repulsive-based-on-the-inverse-square-law particle simulation I came across this, which is basically a really simple model of gravity. You tell it how many balls you want it to start with, which are then placed at random points on the screen with zero momentum and a mass of 4. Then the simulation starts, running one time step of the simulation and redrawing the screen, then repeating this indefinitely. Particles which collide coalesce into a single particle with the combined mass and momentum of the original. This results in one of three things happening, either all of the masses coalesce into a big, stationary ball (since the net momentum is zero, due to the law of conservation of momentum), two or more masses form a somewhat stable orbit around each other, or one or masses hit the edge of the window during the simulation and 'reflect' (the vector of their velocity perpendicular to the edge is reversed) which breaks the physical simulation by violating conservation of momentum. After this third scenario all hell can break loose, usually resulting in everything coalescing into a huge ball, moving with momentum twice the magnitude of that which was flipped by hitting the wall, and opposite in direction.

Anyway, I looked through the short source file and had a bit of a play. Eventually I gave particles a colour which changes subtley every time they are drawn. I also disabled the old-frame-removing screen fill, allowing each frame of the animation to build upon the previous and create a trail. A little simple colour-cycle logic and I the following patterns appeared to my delight :D

HERE'S THE SOURCE (not properly licensed due to original author. Let's say you can treat is as Public Domain to save complications of licenses)

No comments: