I am currently developing a game that has balls of different radii and mass. My code works properly when all balls are of the same mass; but if i introduce a ball with a greater mass, the results are unexpected and incorrect. Please help me find my flaw.
the AS:
ballHelp.as
the swf:
Ball.swf ( [URL=“http://jnuwebsites.com/help/Ball.html”]swf in html )
The problem is that most of the time the reaction to collision is accurate, but occasionally the two balls will ‘stick’ together. This only seems to happen when one has a larger mass (i think. Here is a swf of two equal mass balls for comparison.
Below is the main collision function which is triggered if the distance between the two balls is greater than the sum of thier radii:
public function doPhysicsTransform(b1:Ball,b2:Ball) {
var bounce = -.9;
var distx = b2.x-b1.x;
var disty = b2.y-b1.y;
var distSQ = distx*distx+disty*disty;
var angle = Math.atan2(disty, distx);
var dist = Math.sqrt(distSQ);
var cosa = Math.cos(angle);
var sina = Math.sin(angle);
var b1vxp = b1.dx*cosa+b1.dy*sina;
var b1vyp = b1.dy*cosa-b1.dx*sina;
var b2vxp = b2.dx*cosa+b2.dy*sina;
var b2vyp = b2.dy*cosa-b2.dx*sina;
var P = b1vxp*b1.m+b2vxp*b2.m;
var V = b1vxp-b2vxp;
b1vxp = (P-b2.m*V)/(b1.m+b2.m);
b2vxp = V+b1vxp;
b1.dx = (b1vxp*cosa-b1vyp*sina)*-bounce;
b1.dy = (b1vyp*cosa+b1vxp*sina)*-bounce;
b2.dx = (b2vxp*cosa-b2vyp*sina)*-bounce;
b2.dy = (b2vyp*cosa+b2vxp*sina)*-bounce;
var diff = (b1.radius+b2.radius)-dist;
b1.x -= Math.cos(angle)*diff/2;
b1.y -= Math.sin(angle)*diff/2;
b2.x += Math.cos(angle)*diff/2;
b2.y += Math.sin(angle)*diff/2;
}
This code was derived from an old discussion on billiards physics. Again any help is much appreciated.
That last section of code is to move the balls apart so that their edges are touching rather than overlaping. I think the issue might be in there somewhere, but i am not certain what the problem is. Please help, thanks.