N-Body Gravitation
snipped by lolablissie
Here is a function for animating the n-body gravitational force between bodies:
public function animate(planetA:Array):void{ var len:int = planetA.length; for(var k:int=0; k<len; k++){ var p:Planet = planetA[k]; for(var m:int=k+1; m<len; m++){ var q:Planet = planetA[m]; var a = q.scaling/(Math.pow(p.xo - q.xo, 2) + Math.pow(p.yo - q.yo, 2)); var theta = Math.atan2(q.yo - p.yo, q.xo - p.xo); p.ax = a*Math.cos(theta); p.ay = a*Math.sin(theta); p.vx += p.ax; p.vy += p.ay; p.xo += p.vx; p.yo += p.vy; } if(p.xo>800||p.xo<0||p.yo>800||p.yo<0){ planetA.splice(k, 1); len--; } this.graphics.drawCircle(p.xo, p.yo, p.scaling/20); } }
class Planet extends Sprite{ public var scaling:Number = Math.random()*100 + 50; public var vx:Number = (Math.random()*1)-0.5; public var vy:Number = (Math.random()*1)-0.5; public var ax:Number = 0; public var ay:Number = 0; public var xo:Number = 0; public var yo:Number = 0; public function Planet():void{ this.graphics.beginFill(0xcc0000, 1); this.graphics.drawCircle(0,0,scaling); this.graphics.endFill(); } }




