Monday, 23 January 2012

Circle collision detection in Actionscript 3

In this post I will show an example of collision detection with circles in Actionscript 3. The example will generate a finite number of circles with random: x, y and radius properties based on the available space of the stage dimensions.

To check for collisions I have calculated the distance between two points using the Pythagorean Theorem. Once I have the distance between two circles I can compare with the circles radius. If the distance is less than the radius then the circle has collided.

var circlesArray:Array = new Array();
var count:int = -1;

var timer:Timer = new Timer(100);
timer.addEventListener(TimerEvent.TIMER, timerHandler);
timer.start();

 
function createCircles()
{
 var overlap:Boolean = true;
 var attempts:int = 100;
 
 while(overlap)
 {
  attempts--
  overlap = false;

  var xpos:int = int(Math.random() * stage.stageWidth);
  var ypos:int = int(Math.random() * stage.stageHeight);
  var radius:int = int(5+Math.random()*60);
  
  for(var i:int = 0; i < circlesArray.length; i++){
   var distance = DistanceTwoPoints(xpos, circlesArray[i].xpos, ypos, circlesArray[i].ypos);

   if(distance < radius + circlesArray[i].r){
    overlap = true;
   }
  }
 }
 
    circlesArray.push({xpos: xpos, ypos: ypos, r: radius});
    return attempts>0?circlesArray:false;

}

function timerHandler(e:TimerEvent):void
{
 if(!createCircles()){
  timer.stop();
  trace('all done');
 }else{
  count++;
  var c:Shape = new Shape();
  c.graphics.beginFill(Math.random() * 0xffffff);
  c.graphics.drawCircle(circlesArray[count].xpos,circlesArray[count].ypos,circlesArray[count].r);
  c.graphics.endFill();
  addChild(c);
 }
}


function DistanceTwoPoints(x1:Number, x2:Number,  y1:Number, y2:Number):Number 
{
    var dx:Number = x1-x2;
    var dy:Number = y1-y2;
    return Math.sqrt(dx * dx + dy * dy);
}

As you see in the example below. The circle shapes keep generating until the available stage space has been taken up.

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP