Jan
1
2010

# Solar Flexus

I’ve wanted to write a physics engine for years and messing with Squeak made me want to try it in Flex. It wasn’t quite as easy as Squeak but it wasn’t too hard.

(It probably needs flash 10 to work)

So far I have gravity and collisions for circular objects. Up next: drag.

Here’s the main loop:

```[sourcecode language='js'] public function tick() :void { for each(var body :Body in bodies) { var force :Point = calculateForceOn(body); body.apply(force); body.move(1);```

``` ```

``` checkForCollision(body); } } [/sourcecode]```

Inverse Square Law to calculate gravity:

```[sourcecode language='js'] public function calculateForceOn(body :Body) :Point { var force :Point= new Point(0, 0);```

``` for each(var other :Body in bodies) { if(body != other) { var distance :Number = Point.distance(body.position,other.position); var magnitude :Number = (body.mass+other.mass) /(distance*distance); var direction :Point = other.position.subtract(body.position); var additionalForce :Point = new Point(direction.x*magnitude/distance, direction.y*magnitude/distance); force = force.add(additionalForce); } } ```

``` return force; } [/sourcecode]```

Look for collisions and calculate the impulsive forces:

```[sourcecode language='js'] public function checkForCollision(body :Body) :void { for each(var other :Body in bodies) { if(body != other && body.intersects(other)) { var normal :Point = body.findCollisionNormalTo(other);```

``` var relativeVelocity :Point= body.findVelocityRelativeTo(other); var relativeNormalVelocity :Number = dotProduct(relativeVelocity, normal); ```

``` if(relativeNormalVelocity < 0) { var impulse :Number = -dotProduct(normal,relativeVelocity) *(coefficientOfRestitution+1) /(1/body.mass+1/other.mass); body.applyImpulse(impulse, normal); other.applyImpulse(-impulse, normal); } } } } [/sourcecode]```

And some heavenly bodies:

```[sourcecode language='js'] var sun :Body = new Body("Sun", World.Origin); sun.radius = 60; sun.mass = 50000; sun.color = 0x26393D;```

``` var earth :Body = new Body("Earth", new Point(0,500)); earth.radius = 40; earth.mass = 4; earth.velocity = new Point(5,0); earth.color = 0xE8E595; ```

``` world.add(sun); world.add(earth); world.add(moon); world.add(mars); [/sourcecode]```

I am still not sure whether I like Flex. The libraries are fantastic but the language - ActionScript - is super-annoying. It makes me wish for C#. It's allegedly a dynamic language but the compiler makes you declare every type anyway in that wacky syntax that I can never quite remember. Simulating solar systems is fun though.