I have a program in which circles can bounce off of each other. I followed directions from here to rotate vectors and scale values based on the angle of collision: http://www.vobarian.com/collisions/2dcollisions2.pdf
I wrote this code in python (index 0 indicates 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])]
The problem is that it works sometimes, but not at another time. Can someone tell me why? It seems that if the balls collide at right angles, then their output paths change or something like that. I wrote this in a browser browser: http://www.codeskulptor.org/#user39_8q0Xdp3Y4s_2.py
Can someone point out where I made a mistake?
EDIT: Could I handle the collision? Here are 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 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:
source share