Thanks for that, but Grrrrrr. My algorithm only works in one dimension. Please tell me what I'm doing wrong, I've spent two days on this trivial part of my program.
It's GNU C. The structure of the particles should be obvious:
x, y are position
vx, vy are velocity along the axis
Code:
//get the normal to the collision
float dx = spheres[p1].x - spheres[p2].x;
float dy = spheres[p1].y - spheres[p2].y;
float theta = atan2(dx, dy);
//get the angle of the Velocities
float vangle1 = atan2(spheres[p1].vx, spheres[p1].vy);
float vangle2 = atan2(spheres[p2].vx, spheres[p2].vy);
//rotate the angles into the normal to collision axis
vangle1 = vangle1 - theta;
vangle2 = vangle2 - theta;
//Pull out the velocities' magnitude
float u1 = Velocity(p1);
float u2 = Velocity(p2);
//change velocity vectors to new coordinate system
spheres[p1].vx = sinf(vangle1) * u1;
spheres[p1].vy = cosf(vangle1) * u1;
spheres[p2].vx = sinf(vangle2) * u2;
spheres[p2].vy = cosf(vangle2) * u2;
//take out mass so the forumula is easier to read
float m1 = spheres[p1].mass;
float m2 = spheres[p2].mass;
//handle velocities for the new x axis
float v1 = (spheres[p1].vx * (m1 - m2) + (2 * m2 * spheres[p2].vx)) / (m1 + m2);
float v2 = (spheres[p2].vx * (m2 - m1) + (2 * m1 * spheres[p1].vx)) / (m1 + m2);
spheres[p1].vx = v1;
spheres[p2].vx = v2;
//handle velocities for the new y axis
v1 = (spheres[p1].vy * (m1 - m2) + (2 * m2 * spheres[p2].vy)) / (m1 + m2);
v2 = (spheres[p2].vy * (m2 - m1) + (2 * m1 * spheres[p1].vy)) / (m1 + m2);
spheres[p1].vy = v1;
spheres[p2].vy = v2;
//get the angle of the new Velocities (still in new coordinate system)
vangle1 = atan2(spheres[p1].vx, spheres[p1].vy);
vangle2 = atan2(spheres[p2].vx, spheres[p2].vy);
//rotate back into x/y coordinate system
vangle1 = vangle1 + theta;
vangle2 = vangle2 + theta;
//Pull out the velocities' magnitude from the collision coordinate system
u1 = Velocity(p1);
u2 = Velocity(p2);
//change velocity vectors back to x/y coordinate system
spheres[p1].vx = sinf(vangle1) * u1;
spheres[p1].vy = cosf(vangle1) * u1;
spheres[p2].vx = sinf(vangle2) * u2;
spheres[p2].vy = cosf(vangle2) * u2;
I know it's bad code
I'm from the school of make it work, then make it fast
Bookmarks