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){