N-Body Gravitation

November 27th, 2008 by steamfrog

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();
				}

 
		}


Get this code and tons more at
http://www.actionsnip.com/

Share and Enjoy:

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • ThisNext
  • MisterWong
  • Wists
  • blinkbits
  • BlinkList
  • blogmarks
  • Fark
  • Fleck
  • Furl
  • IndiaGram
  • IndianPad
  • Linkter
  • Ma.gnolia
  • NewsVine
  • Reddit
  • Simpy
  • Slashdot
  • Smarking
  • SphereIt
  • Spurl
  • StumbleUpon
  • Taggly
  • TailRank
  • Technorati
  • YahooMyWeb

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.