you're doing way more than you need to here (with a decent amount of computational overhead), and making it difficult to solve for a non-elastic response. this might be fairly long-winded, but will give you a solution, and one that performs a lot better.
firstly, you always want to avoid computing a square root wherever possible- you can check to see if the circles are intersecting by checking the square of the distance between them against the squared sum of their radii:
so then you want to solve for the impulse, which is a scalar and effected by the coefficient of restitution. each object should have this defined within the bounds 0 <= e <= 1.Code://i don't know what data type you're using- dynamic MovieClips? var car1:Object = cararray[ i1 ]; var car2:Object = cararray[ i2 ]; var diffx:Number = car1.x - car2.x; var diffy:Number = car1.y - car2.y; if( diffx * diffx + diffy * diffy <= cardiameter * cardiameter ) { //circles colliding }
happy to help out if anything's unclear. this should be a lot faster as it has no trigonometric function calls and less multiplication too.Code:var restitution:Number = ( car1.e + car2.e ) * 0.5; //relative velocity var rvx:Number = car1.velx - car2.velx; var rvy:Number = car1.vely - car2.vely; //if their relative velocity along the collision normal is greater than or equal to zero, //they are moving apart, we shouldn't try to resolve a collision n this situation as it //could cause sticking, especially when close to zero if( rvx * diffx + rvy * diffy >= 0 ) return; //if we're this far in the algorithm, we're definitely going to apply a collision response //so it's fair to make a square root call- we need the normalized collision normal var length:Number = Math.sqrt( diffx * diffx + diffy * diffy ); //diff becomes the normalized collision normal diffx /= length; diffy /= length; //you should store an inverse mass property on each car too- 1 / mass var invMassSum:Number = car1.invMass + car2.invMass; var denominator:Number = diffx * diffx * invMassSum + diffy * diffy * invMassSum; //now we can solve for the impulse var impulsex:Number = diffx * rvx * -( 1 + restitution ); var impulsey:Number = diffy * rvy * -( 1 + restitution ); impulsex /= denominator; impulsey /= denominator; //add the impulse to each circle's velocity car1.velx += impulsex * car1.invMass; car1.vely += impulsey * car1.invMass; //i just changed, this, had this as car1 by accident car2.velx -= impulsex * car2.invMass; car2.vely -= impulsey * car2.invMass;




Reply With Quote