Hello everyone im trying to solve a problem ive been having, I have been developing a 2d billiards game and have run into a problem as anyone who has tried to make a billiards game before probably knows all too well. Anyways here is a link to my .swf (http://www.swfcabin.com/open/1277161886) to demonstrate my problem, when you blast the cue ball at any ball on the table if the cue ball travels two much in between the current frame and the last frame it will overlap the ball being hit and will stick and rotate.
heres the code every frame I loop threw all the balls on table to check for a collision.
private function enterFrameHandler( E:Event ):void {
for (var i = 0; i < mcBallContainer.numChildren; i++) {
var mcBall1:* =mcBallContainer.getChildAt(i);
for (var j = i + 1; j < mcBallContainer.numChildren; j++) {
var mcBall2:* =mcBallContainer.getChildAt(j);
solveBalls( mcBall2, mcBall1 );
}
}
}
then the solveBalls function
private function solveBalls( MCBallA:MovieClip, MCBallB:MovieClip ):void {
if(detect(MCBallA, MCBallB) == true)
{
react(MCBallA, MCBallB);
}
}
here is the collision detections
private function detect(a:MovieClip , b:MovieClip) : Boolean
{
var cDiff:Point = new Point( b.Position.x - a.Position.x, b.Position.y - a.Position.y );
var c:Number = Math.sqrt(cDiff.x * cDiff.x + cDiff.y * cDiff.y);
if (c<a.radius+b.radius)
{
return true;
}
return false;
}
and finally the reaction code
public function react( a:MovieClip, b:MovieClip ):void {
var nX1:Number=a.x;
var nY1:Number=a.y;
var nDistX1:Number=b.x-nX1;
var nDistY1:Number=b.y-nY1;
var nDistance1:Number=Math.sqrt(nDistX1*nDistX1+nDistY1*nDistY1);
var nRadiusA:Number=a.width/2;
var nRadiusB:Number=b.width/2;
var nNormalX:Number;
var nNormalY:Number;
var nMidpointX:Number;
var nMidpointY:Number;
var nVector:Number;
var nVelX:Number;
var nVelY:Number;
nNormalX=nDistX1/nDistance1;
nNormalY=nDistY1/nDistance1;
nMidpointX = ( nX1 + b.x )/2;
nMidpointY = ( nY1 + b.y )/2;
a.x=nMidpointX-nNormalX*nRadiusA;
a.y=nMidpointY-nNormalY*nRadiusA;
b.x=nMidpointX+nNormalX*nRadiusB;
b.y=nMidpointY+nNormalY*nRadiusB;
nVector = ( ( a.nSpeedX - b.nSpeedX ) * nNormalX )+ ( ( a.nSpeedY - b.nSpeedY ) * nNormalY );
nVelX=nVector*nNormalX;
nVelY=nVector*nNormalY;
a.nSpeedX-=nVelX;
a.nSpeedY-=nVelY;
b.nSpeedX+=nVelX;
b.nSpeedY+=nVelY;
}
every frame the balls update positions by
nSpeedX*=0.97;
nSpeedY*=0.97;
this.x-=nSpeedX;
this.y-=nSpeedY;
please if anyone has the solution to this problem or any insight at all, I would be forever in your debt. many thanks