Wednesday, 10 August 2011

Remove Box2D bodies in Actionscript 3

In my last post I added Box2D bodies on the stage. In this one I will be removing Box2D bodies from the stage in Actionscript 3. The first example will remove any object on the stage with a mouse click regardless. The objects will be removed using the DestroyBody() method. I have used code my previous post. In the constructor add the mouse click event. You will also need to import the MouseEvent class.

stage.addEventListener(MouseEvent.CLICK,destroyB2Body);

The destroyB2Body function gets the x and y mouse positions in pixels. The QueryPoint method queries for any fixtures by a mouse click. The first parameter is the callback function and the second is the mouse x and y position.

The queryCallBack function gets the body from the fixture, and the DestroyBody method removes the body from the stage.

private function destroyB2Body(e:MouseEvent):void
{
 var px:Number = mouseX / PIXEL_TO_METRE;
 var py:Number = mouseY / PIXEL_TO_METRE;
 world.QueryPoint(queryCallBack, new b2Vec2(px, py));
}

private function queryCallBack(fixture:b2Fixture):Boolean
{
 var body:b2Body = fixture.GetBody();
 world.DestroyBody(body);
 return false;
}

In the second example you can specify which object to be removed from stage. In the createBox and createSphere function add an additional parameter and add the following code inside each function. This will store a custom attribute to the bodies, so we can check which bodies to be removed.

bodyDef.userData = new Object(); 
bodyDef.userData.name = s; 

Then update the following code in the constructor. I have added the string 'stay' or 'remove' for the bodies to be removed. The queryCallBack function has been updated to remove only bodies with the attribute name 'remove'.

createBox(0, 370, 550, 30, 'stay', b2Body.b2_staticBody);
createSphere(150, 130, 30, 'stay', b2Body.b2_dynamicBody, 10, 0.1, 0.7);
createSphere(240, 130, 30, 'remove', b2Body.b2_dynamicBody, 3, 0.4, 0.3);
createSphere(330, 130, 30, 'remove', b2Body.b2_dynamicBody, 5, 0.4, 0.4);

private function queryCallBack(fixture:b2Fixture):Boolean
{
 var body:b2Body = fixture.GetBody();
 if (body.GetUserData().name == 'remove')
 {
  world.DestroyBody(body);
 }
 return false;
}

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP