Skip to content

Instantly share code, notes, and snippets.

@djcsdy
Created March 7, 2011 01:17
Show Gist options
  • Save djcsdy/857940 to your computer and use it in GitHub Desktop.
Save djcsdy/857940 to your computer and use it in GitHub Desktop.
Rough implementation of fully-elastic collision. Only modifies the position and velocity of sprite 1; the assumption is that this code will get run again with the sprites swapped round. The stuff in actionQueue.enqueue should get run after all collisions
var sprite2ToSprite1:FlxPoint = VectorMath.subtract(sprite1.centre, sprite2.centre);
var sprite2ToSprite1UnitVector:FlxPoint = VectorMath.normalize(sprite2ToSprite1);
var sprite2SpeedTowardsSprite1:Number = VectorMath.dotProduct(sprite2.velocity, sprite2ToSprite1UnitVector);
var sprite1ToSprite2UnitVector:FlxPoint = VectorMath.negate(sprite2ToSprite1UnitVector);
var sprite1SpeedTowardsSprite2:Number = VectorMath.dotProduct(sprite1.velocity, sprite1ToSprite2UnitVector);
var sumOfThoseSpeeds:Number = sprite1SpeedTowardsSprite2 + sprite2SpeedTowardsSprite1;
var sprite1VelocityChange:FlxPoint =
VectorMath.multiply(sprite2ToSprite1UnitVector, sumOfThoseSpeeds/2);
var distance:Number = VectorMath.magnitude(sprite2ToSprite1);
var distanceAdjustment:Number = ((sprite1.width + sprite2.width)/2 - distance)/2 + 1;
if (distanceAdjustment < 0) {
distanceAdjustment = 0;
}
var adjustmentVector:FlxPoint = VectorMath.multiply(
sprite2ToSprite1UnitVector, distanceAdjustment);
if (sumOfThoseSpeeds > 0) {
actionQueue.enqueue(function () :void {
sprite1.velocity = VectorMath.add(sprite1.velocity, sprite1VelocityChange);
sprite1.x += adjustmentVector.x;
sprite1.y += adjustmentVector.y;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment