Wednesday, 4 July 2012

Quickbox2D collision detection

In this quick post I will provide code for Quickbox2D collision detection in Actionscript 3. Firstly, I will detect the collision between two circle objects and trace a message when the contact occurs. Here is my code below.

import com.actionsnippet.qbox.*;

//Variables
var PIXELS_TO_METERS:uint = 30;
var STAGE_WIDTH:uint = 800;
var STAGE_HEIGHT:uint = 600;

//Create new instance of the QuickBox2D class
var sim:QuickBox2D = new QuickBox2D(this);

//Draws the edges around the stage
sim.createStageWalls();

//Create two circle objects
var circleA:QuickObject = sim.addCircle({x:pToM(100), y:pToM(100), radius:1, fillColor:0xff0000});
var circleB:QuickObject = sim.addCircle({x:pToM(600), y:pToM(100), radius:0.5, fillColor:0x00ff00});

//This listens for when the add events get dispatched.
var contact:QuickContacts = sim.addContactListener();
contact.addEventListener(QuickContacts.ADD, addHandler);

//Display message when objects collide
function addHandler(e:Event):void
{
 if(contact.isCurrentContact(circleA, circleB))
 {
  trace('circles collided');
 }
 
}

sim.start();
sim.mouseDrag();


//Utility function to convert pixels to meters
function pToM(pixels:Number):Number
{
 return pixels * (1 / PIXELS_TO_METERS);
}

The same collision detection code can also be applied to multiple objects. The code below will trace a message when any of the ten circleB objects collide with the circleA objects. I have only included the updated code snippets below.

var circlesArray:Array = new Array();
var NUM_CIRCLES:uint = 10;

var circleA:QuickObject = sim.addCircle({x:pToM(100), y:pToM(100), radius:1, fillColor:0xff0000});

for(var i:uint = 0; i < NUM_CIRCLES; i++)
{
 var circleB:QuickObject = sim.addCircle({x:pToM(600), y:pToM(100), radius:0.5, fillColor:0x00ff00});
 circlesArray.push(circleB);
}

function addHandler(e:Event):void
{
 for(var i:uint = 0; i < NUM_CIRCLES; i++){
  if(contact.isCurrentContact(circleA, circlesArray[i]))
  {
   trace('circles collided');
  }
 }

}

There are two more types of contact event that be dispatched: REMOVE and PERSIST. The REMOVE event gets called when a QuickObject is no longer touching. The PERSIST event gets called when a QuickObject collides and is still touching.

var contact:QuickContacts = sim.addContactListener();
contact.addEventListener(QuickContacts.PERSIST, persistHandler);
contact.addEventListener(QuickContacts.REMOVE, removeHandler);

function persistHandler(e:Event):void
{
 for(var i:uint = 0; i < NUM_CIRCLES; i++){
  if(contact.isCurrentContact(circleA, circlesArray[i]))
  {
   trace('circles touching');
  }
 }
}

function removeHandler(e:Event):void
{
 for(var i:uint = 0; i < NUM_CIRCLES; i++){
  if(contact.isCurrentContact(circleA, circlesArray[i]))
  {
   trace('circles not touching');
  }
 }
}

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP