I am trying to calculate the collision of 2 balls of equal mass, assuming the collision is perfectly elastic, for a computer physics simulation. Given the coordinates of both balls and their initial velocities at the time of the collision, I want to calculate the final velocities. I searched around for a while online and found a few different websites give a formula for doing this. The problem is that when running the simulation, it seemed that kinetic energy was not being properly conserved (some collisions where adding energy which makes no sense at all, some losing it). So my question is: Is their something wrong with this method? Here is pseudo code for the method:
function manage_bounce(ball, ball2) {
dx = ball._x-ball2._x;
dy = ball._y-ball2._y;
collisionision_angle = Math.atan2(dy, dx);
magnitude_1 = Math.sqrt(ball.xspeed*ball.xspeed+ball.yspeed*ball.yspeed);
magnitude_2 = Math.sqrt(ball2.xspeed*ball2.xspeed+ball2.yspeed*ball2.yspeed);
direction_1 = Math.atan2(ball.yspeed, ball.xspeed);
direction_2 = Math.atan2(ball2.yspeed, ball2.xspeed);
new_xspeed_1 = magnitude_1*Math.cos(direction_1-collisionision_angle);
new_yspeed_1 = magnitude_1*Math.sin(direction_1-collisionision_angle);
new_xspeed_2 = magnitude_2*Math.cos(direction_2-collisionision_angle);
new_yspeed_2 = magnitude_2*Math.sin(direction_2-collisionision_angle);
final_xspeed_1 = ((ball.mass-ball2.mass)*new_xspeed_1+(ball2.mass+ball2.mass)*new_xspeed_2)/(ball.mass+ball2.mass);
final_xspeed_2 = ((ball.mass+ball.mass)*new_xspeed_1+(ball2.mass-ball.mass)*new_xspeed_2)/(ball.mass+ball2.mass);
final_yspeed_1 = new_yspeed_1;
final_yspeed_2 = new_yspeed_2;
ball.xspeed = Math.cos(collisionision_angle)*final_xspeed_1+Math.cos(collisionision_angle+Math.PI/2)*final_yspeed_1;
ball.yspeed = Math.sin(collisionision_angle)*final_xspeed_1+Math.sin(collisionision_angle+Math.PI/2)*final_yspeed_1;
ball2.xspeed = Math.cos(collisionision_angle)*final_xspeed_2+Math.cos(collisionision_angle+Math.PI/2)*final_yspeed_2;
ball2.yspeed = Math.sin(collisionision_angle)*final_xspeed_2+Math.sin(collisionision_angle+Math.PI/2)*final_yspeed_2;
}