Math and (Quasi) Physics in Action Script 3

Box 2D - simulation of falling balls

Simple demonstration of twenty balls bouce on the floor.

Clicking on the stage restarts the movie.

Main.as

´╗┐package {
  import Box2D.Collision.b2AABB;
  import Box2D.Collision.Shapes.*;
  import Box2D.Common.Math.b2Vec2;
  import Box2D.Dynamics.b2Body;
  import Box2D.Dynamics.b2BodyDef;
  import Box2D.Dynamics.b2DebugDraw;
  import Box2D.Dynamics.b2World;
  import flash.display.Sprite;
  import flash.events.Event;
  import flash.events.MouseEvent;



  public class Main extends Sprite {
    private var world:b2World;
    private var fps:uint;
    public function Main():void {
      fps = stage.frameRate;
      stage.addEventListener(MouseEvent.CLICK, init);
      addEventListener(Event.ENTER_FRAME, h_enterFrame);
      init();
    }
    private function init(event:MouseEvent = null):void {

      // create the world
      var worldAABB:b2AABB = new b2AABB();
      worldAABB.lowerBound.Set(-100, -100);
      worldAABB.upperBound.Set(100, 100);
      var gravity:b2Vec2 = new b2Vec2(0,10);
      world = new b2World(worldAABB,gravity,true);

      // create a floor box
      var floorBodyDef:b2BodyDef = new b2BodyDef();
      floorBodyDef.position.Set(2.5, 4.5);
      var floorShapeDef:b2PolygonDef = new b2PolygonDef();
      floorShapeDef.SetAsBox(2, 0.05);
      var floor:b2Body = world.CreateBody(floorBodyDef);
      floor.CreateShape(floorShapeDef);

      // create balls
      var circleBodyDef:b2BodyDef;
      var circleShapeDef:b2CircleDef;
      var circleBody:b2Body;
      for (var i:uint = 0; i < 20; i ++) {
        circleBodyDef = new b2BodyDef();
        circleBodyDef.position.Set(Math.random() * 2 + 1.5, Math.random() * 0.5);
        circleShapeDef = new b2CircleDef();
        circleShapeDef.radius = 0.1;
        circleShapeDef.density = 1;
        circleShapeDef.restitution = 0.5;
        circleBody = world.CreateBody(circleBodyDef);
        circleBody.CreateShape(circleShapeDef);
        circleBody.SetMassFromShapes();
      }

      var debugDraw:b2DebugDraw = new b2DebugDraw();
      debugDraw.m_sprite = this;
      debugDraw.m_drawScale = 100;
      debugDraw.m_fillAlpha = 0.3;
      debugDraw.m_lineThickness = 1;
      debugDraw.m_drawFlags = b2DebugDraw.e_shapeBit;
      world.SetDebugDraw(debugDraw);
    }

    private function h_enterFrame(event:Event):void {
      if (world == null) {
        return;
      }
      world.Step(1 / fps, 10);
    }
  }
}