Brian Chia
       
 
categories
actionscript
actionscript 1.0
actionscript 2.0
misc
 
processing
 
links
brian chia
kelvin zhao
ronald leong
 
 
Multi Collision
 

To ensure the efficiency of the code. We had to change the inital and end values of the 2 loops:

for(var i:Number=0;i<num-1;i++){

for(var n:Number=i+1;n<num;n++){

// check for collision

}

}

For the 1st loop (outer loop) it loop one less. The last clip will not need to be tested for collision as it will be tested before that. As for the 2nd loop (inner loop), it will start for the value of 1+1. This is because any object whose index is lower or same as i is already tested.

In this way, redundant collision checks is remove and performance will be enhance. Another reason to remove this double collision check is that it can lead to double executation of collision script.


import Vector;

// balls count
var num:Number=6;

// declare properties for each ball

var i:Number=num;
while(i--){

var ball:MovieClip=attachMovie("ball_mc","ball"+i,getNextHighestDepth());
// position the ball randomly on screen
ball._x=Math.round(Math.random()*Stage.width);
ball._y=Math.round(Math.random()*Stage.height);

ball.r=ball._width/2;
ball.v=new Vector(5,5);

}

this.onEnterFrame=function():Void{

// multi collision
// loop thru every object except the last object

for(var i:Number=0;i<num-1;i++){

// 1st object ref
var ball:MovieClip=this["ball"+i];

// loop thru every object after i
for(var n:Number=i+1;n<num;n++){

// 2nd object ref
var ball1:MovieClip=this["ball"+n];

// check for collision
var dx:Number=ball1._x-ball._x;
var dy:Number=ball1._y-ball._y;
var d:Number=Math.sqrt(dx*dx+dy*dy);
var md:Number=ball.r+ball1.r;
if(d<md){

ball.v.reverse();
ball1.v.reverse();

}

}

}

var i:Number=num;
while(i--){

this["ball"+i]._x+=this["ball"+i].v.vx;
this["ball"+i]._y+=this["ball"+i].v.vy;

// check for border and rebounce back
checkBorder(this["ball"+i]);

}

}

function checkBorder(mc:MovieClip):Void{

// reflect from x axis
if(mc._x<mc.r || mc._x>Stage.width-mc.r){

mc._x=mc._x<Stage.width-mc.r ? mc.r:Stage.width-mc.r;
mc.v.reset(-mc.v.vx,mc.v.vy);

}

// reflect from y axis
if(mc._y<mc.r || mc._y>Stage.height-mc.r){

mc._y=mc._y<Stage.height-mc.r ? mc.r:Stage.height-mc.r;
mc.v.reset(mc.v.vx,-mc.v.vy);

}

}



suggestion

 
 
 
         
  © copyright 2007 THINKLUNATIC.    
Brian Chia Jonathan Ng