How to add sprite to a body in Box2D in Adobe AIR, FLEX and FLASH? Or Add image/Sprite to a body in ActionScript.

By | April 12, 2012

The below code is for FlashBuilder 4, If you are using FlexBuilder3 use addChild()
instead of the commented block in the following code.

public function addCircle(){x:Number, y: Number, radius:Number, ballcip:Ball):void{

bd:b2BodyDef = new b2BodyDef();

      var loader:Loader = new Loader();

      loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,
                                                           imageFailed);
      var request:URLRequest = new URLRequest("ball.png");
      loader.load(request);

      /*optionally change the position of the image if not fitting in the body */
      /* You can also rotate the image.*/
      loader.x = -50;
      loader.y = -50;

      /***************************************/
      var ui:UIComponent = new UIComponent();
      ui.addChild(loader);
      this.addElement(ui);
      /**************************************/

      bd.userData = ui;
      bd.position.Set(_x/m_phys_scale, _y/ m_phys_scale);
      bd.type=b2Body.b2_dynamicBody;
      var ball_shape:b2CircleShape=new b2CircleShape(50/world_scale);
      var ball_fixture:b2FixtureDef = new b2FixtureDef();
      ball_fixture.shape=ball_shape;
      ball_fixture.friction=0.9;
      ball_fixture.density=30;
      ball_fixture.restitution=0.3;
      ball_body=world.CreateBody(bd);
      ball_body.CreateFixture(ball_fixture);
}

private function imageFailed(event:IOErrorEvent):void
{
      Alert.show("Image loading failed"); //make sure you have the image.
}

Leave a Reply

Your email address will not be published. Required fields are marked *