In my example for Multi Collision, you might notice that some of the balls get stuck together. This is a common scene due to the intersect area between the 2 collide balls are greater than the velocities.
Wrote the following code to reposition the balls where they just touch each other when they collide:
// find the 2 vectors magnitude
var vl:Number=ball1.v.vLength+ball2.v.vLength;
// find the intersect distance
var id:Number=(ball1.r+ball2.r)-dist;
// create another set of vectors
var v1:Vector=ball1.v.clone();
var v2:Vector=ball2.v.clone();
// find the ratio of the magnitude
v1.vLength=ball1.v.vLength/vl*id;
v2.vLength=ball2.v.vLength/vl*id;
// reposition the ball position
ball1._x-=v1.vx;
ball1._y-=v1.vy;
ball2._x-=v2.vx;
ball2._y-=v2.vy;
import Vector;
// create num of balls var numBalls:Number=15; for(var i:Number=0;i<numBalls;i++){
var ball:MovieClip=attachMovie("ball_mc","ball"+i,getNextHighestDepth());
ball.m=Math.random()*3+2;
ball._xscale=ball._yscale=ball.m*100;
ball.r=ball._width/2;
ball.v=new Vector(Math.random()*10-5,Math.random()*10-5);
// to ensure no balls is touching each other before start of movie for(var j:Number=0;j<i;j++){
var ballC:MovieClip=this["ball"+j]; var dx:Number=ballC._x-ball._x; var dy:Number=ballC._y-ball._y; var d:Number=Math.sqrt(dx*dx+dy*dy);
if(d<ball.r+ballC.r){
ball.removeMovieClip();
i=i-1; break;
}
}
}
this.onEnterFrame=function():Void{
// move the balls and check for border for(var i:Number=0;i<numBalls;i++){
var ball:MovieClip=this["ball"+i];
ball._x+=ball.v.vx;
ball._y+=ball.v.vy;
checkBorder(ball);
}
// check for multi collision for(var i:Number=0;i<numBalls-1;i++){
var ball1:MovieClip=this["ball"+i]; for(var j:Number=i+1;j<numBalls;j++){
var ball2:MovieClip=this["ball"+j];
checkCollision(ball1,ball2);
}
}
}
function checkCollision(ball1:MovieClip,ball2:MovieClip):Void{
var dx:Number=ball2._x-ball1._x; var dy:Number=ball2._y-ball1._y; var d:Number=Math.sqrt(dx*dx+dy*dy); if(d<ball1.r+ball2.r){
// find the 2 vectors magnitude var vl:Number=ball1.v.vLength+ball2.v.vLength; // find the intersect distance var id:Number=(ball1.r+ball2.r)-d; // create another set of vectors var v1:Vector=ball1.v.clone(); var v2:Vector=ball2.v.clone();
// conservation of momentum var vNw1:Number=((ball1.m-ball2.m)*ball1.v.vx+2*ball2.m*ball2.v.vx)/(ball1.m+ball2.m); var vNw2:Number=((ball2.m-ball1.m)*ball2.v.vx+2*ball1.m*ball1.v.vx)/(ball1.m+ball2.m);
//reset the velocity
ball1.v.reset(vNw1,ball1.v.vy);
ball2.v.reset(vNw2,ball2.v.vy);
// rotate velocity vectors back
ball1.v.rotate(-a);
ball2.v.rotate(-a);
}
}
function checkBorder(mc:MovieClip):Void{
// reflect from x axis if(mc._x<mc.r || mc._x>Stage.width-mc.r){