Resultant Vector Algorithm for 2D Collisions

Posted by John on Game Development See other posts from Game Development or by John
Published on 2012-03-25T00:18:21Z Indexed on 2012/03/29 5:42 UTC
Read the original article Hit count: 325

Filed under:

I am making a Pong based game where a puck hits a paddle and bounces off. Both the puck and the paddles are Circles. I came up with an algorithm to calculate the resultant vector of the puck once it meets a paddle. The game seems to function correctly but I'm not entirely sure my algorithm is correct. Here are my variables for the algorithm:

Given:
velocity = the magnitude of the initial velocity of the puck before the collision
x = the x coordinate of the puck
y = the y coordinate of the puck
moveX = the horizontal speed of the puck
moveY = the vertical speed of the puck

otherX = the x coordinate of the paddle
otherY = the y coordinate of the paddle
piece.horizontalMomentum = the horizontal speed of the paddle before it hits the puck
piece.verticalMomentum = the vertical speed of the paddle before it hits the puck

slope = the direction, in radians, of the puck's velocity
distX = the horizontal distance between the center of the puck and the center of the paddle
distY = the vertical distance between the center of the puck and the center of the paddle

Algorithm solves for:
impactAngle = the angle, in radians, of the angle of impact.
newSpeedX = the speed of the resultant vector in the X direction
newSpeedY = the speed of the resultant vector in the Y direction


Here is the code for my algorithm:

int otherX = piece.x;
int otherY = piece.y;
double velocity = Math.sqrt((moveX * moveX) + (moveY * moveY));

double slope = Math.atan(moveX / moveY);
int distX = x - otherX;
int distY = y - otherY;

double impactAngle = Math.atan(distX / distY);

double newAngle = impactAngle + slope;
int newSpeedX = (int)(velocity * Math.sin(newAngle)) + piece.horizontalMomentum;
int newSpeedY = (int)(velocity * Math.cos(newAngle)) + piece.verticalMomentum;

for those who are not program savvy here is it simplified:

velocity = v(moveX² + moveY²)
slope = arctan(moveX / moveY)
distX = x - otherX
distY = y - otherY

impactAngle = arctan(distX / distY)

newAngle = impactAngle + slope
newSpeedX = velocity * sin(newAngle) + piece.horizontalMomentum
newSpeedY = velocity * cos(newAngle) + piece.verticalMomentum

My Question:
Is this algorithm correct? Is there an easier/simpler way to do what I'm trying to do?

© Game Development or respective owner

Related posts about collision-detection