I have a a program where circles can bounce into one another. I followed the directions from here for rotating the vectors and scaling the magnitudes based on the collision angle: http://www.vobarian.com/collisions/2dcollisions2.pdf
I wrote this code in python (the 0 index indicates the x coordinate):
norm_vect = [(object2.pos[0] - object1.pos[0]), (object2.pos[1] - object1.pos[1])]
unit = sqrt((norm_vect[0]**2) + (norm_vect[1]**2))
unit_vect = [float(norm_vect[0]) / unit, float(norm_vect[1]) /unit]
tan_vect = [-unit_vect[1], unit_vect[0]]
vel1 = object1.vel
vel2 = object2.vel
vel1_norm = vel1[0] * unit_vect[0] + vel1[1] * unit_vect[1]
vel1_tan = vel1[0] * tan_vect[0] + vel1[1] * tan_vect[1]
vel2_norm = vel2[0] * unit_vect[0] + vel2[1] * unit_vect[1]
vel2_tan = vel2[0] * tan_vect[0] + vel2[1] * tan_vect[1]
new_vel1_norm = (vel1_norm * (object1.mass - object2.mass) + 2 * object2.mass * vel2_norm) / (object1.mass + object2.mass)
new_vel2_norm = (vel2_norm * (object2.mass - object1.mass) + 2 * object1.mass * vel1_norm) / (object1.mass + object2.mass)
new_norm_vect1 = [new_vel1_norm * float(unit_vect[0]), new_vel1_norm * float(unit_vect[1])]
new_norm_vect2 = [new_vel2_norm * float(unit_vect[0]), new_vel2_norm * float(unit_vect[1])]
new_tan_vect1 = [new_vel1_norm * float(tan_vect[0]), new_vel1_norm * float(tan_vect[1])]
new_tan_vect2 = [new_vel2_norm * float(tan_vect[0]), new_vel2_norm * float(tan_vect[1])]
# Now update the object's velocity
object1.vel = [new_norm_vect1[0] + new_tan_vect1[0], + new_norm_vect1[1] + new_tan_vect1[1]]
object2.vel = [new_norm_vect2[0] + new_tan_vect2[0], + new_norm_vect2[1] + new_tan_vect2[1]]
The problem is that it works sometimes, but not othertimes. Can anyone tell me why? It seems like if the balls collide at the right angle then their exit trajectories swap or something. I wrote this in codeskulptor browser: http://www.codeskulptor.org/#user39_8q0Xdp3Y4s_2.py
Can anyone point out where I went wrong?
EDIT: Could it be the way that I process the collision? Here is the steps:
1) Draw the balls on the screen
2) Create set of unique pairs of collidable objects
3) For each ball, move the ball's position 1 frame forward according to the velocity:
->1) Check to see if the ball is hitting a wall
->2) For each pairset, if the ball in question is a member of the pair:
-->1) If distance between centers is less than sum of radii:
-->1) Calculate rebound trajectories
---2) Find N such that position + rebound trajectory *N is out of collision zone