Hey, coming to the end of a bit of a nightmare project. One last hurdle.
There are 30-odd balls bouncing around the stage. I have got collision detection code from Kirupa.com (http://www.kirupa.com/developer/actionscript/multiple_collision.htm) which calls some code that determines the direction of the bounce. About 80% of the time it works, but every so often the balls stick together, orbit around each other for a bit and then are flung away. Ive been staring at this and I cant fix it. Could anyone help please?
Code as follows:
Collision Detection:
for (m=0; m<totalObjects; m++) {
circleA = targets[m];
for (n=m+1; n<totalObjects; n++) {
circleB = targets[n];
circleA = eval(circleA);
circleB = eval(circleB);
var xdiff:Number = circleB._x - circleA._x;
var ydiff:Number = circleB._y - circleA._y;
var dist:Number = Math.sqrt(xdiff * xdiff + ydiff * ydiff);
if (dist <= (circleB._width)) {
_root.manage_bounce(circleA, circleB);
}
}
Manage Bounce:
function manage_bounce(ball, ball2) {
dx = ball._x-ball2._x;
dy = ball._y-ball2._y;
angle = Math.atan2(dy, dx);
mag_1 = Math.sqrt(ball.x*ball.x+ball.y*ball.y);
mag_2 = Math.sqrt(ball2.x*ball2.x+ball2.y*ball2.y);
direction_1 = Math.atan2(ball.y, ball.x);
direction_2 = Math.atan2(ball2.y, ball2.x);
new_xspeed_1 = mag_1*Math.cos(direction_1-angle);
new_yspeed_1 = mag_1*Math.sin(direction_1-angle);
new_xspeed_2 = mag_2*Math.cos(direction_2-angle);
new_yspeed_2 = mag_2*Math.sin(direction_2-angle);
final_xspeed_1 = ((ball.mass-ball2.mass)*new_xspeed_1+(ball2.mass+ball2.mass)*new_xspeed_2)/(ball.mass+ball2.mass);
final_xspeed_2 = ((ball.mass+ball.mass)*new_xspeed_1+(ball2.mass-ball.mass)*new_xspeed_2)/(ball.mass+ball2.mass);
final_yspeed_1 = new_yspeed_1;
final_yspeed_2 = new_yspeed_2;
ball.x = Math.cos(angle)*final_xspeed_1+Math.cos(angle+Math.PI/2)*final_yspeed_1;
ball.y = Math.sin(angle)*final_xspeed_1+Math.sin(angle+Math.PI/2)*final_yspeed_1;
ball2.x = Math.cos(angle)*final_xspeed_2+Math.cos(angle+Math.PI/2)*final_yspeed_2;
ball2.y = Math.sin(angle)*final_xspeed_2+Math.sin(angle+Math.PI/2)*final_yspeed_2;
}