Collision.java
The first step is to get ball objects to properly bounce off of the walls.
Then we added a calculation of the intersection of the relative path of one ball with respect to the other with a circle equal to the sum of the two radii.
Finally we added the equations for the changed velocity after impact.
The equations for collisions between elastic particles can be modified to use the COR, thus becoming applicable to both elastic and partially inelastic collisions as well. Note that these equations give the velocity change along the line of centers. The transverse velocities are unchanged.
where
Reference: Coefficient of Restitution, Wikipedia article
public class Collision implements Comparable<Collision> { double timestep; Ball ball1, ball2; int idx; Collision(double t, Ball b1, Ball b2) { timestep = t; ball1 = b1; ball2 = b2; idx = -1; } Collision(double t, Ball b1, int ndx) { timestep = t; ball1 = b1; ball2 = null; idx = ndx; } public String toString() { String str = "timestep " + timestep; if (idx<0) str += " BALL"; return str; } public int compareTo(Collision other) { //Collision c = (Collision) other; if (timestep>other.timestep) return 1; if (timestep<other.timestep) return -1; return 0; } void update_velocity() { if (idx<0) ball_collision(); else wall_collision(); } void wall_collision() { if (idx<2) ball1.vx = -ball1.vx; else ball1.vy = -ball1.vy; } void ball_collision() { double eta = 1.0; // coefficient of restitution // relative position double px = ball2.px - ball1.px; double py = ball2.py - ball1.py; // unit vector along line of centers double vnorm = Math.hypot(px,py); px = px/vnorm; py = py/vnorm; double m1 = ball1.mass; double m2 = ball2.mass; double mt = m1+m2; // velocity components (normal) double v1 = ball1.vx*px+ball1.vy*py; double v2 = ball2.vx*px+ball2.vy*py; // velocity components (transverse) double qx = py; double qy = -px; double u1 = ball1.vx*qx+ball1.vy*qy; double u2 = ball2.vx*qx+ball2.vy*qy; // calculate changed velocity double v1f = ((eta+1.0)*m2*v2+v1*(m1-eta*m2))/mt; double v2f = ((eta+1.0)*m1*v1+v2*(m2-eta*m1))/mt; // back to original coordinates. ball1.vx = v1f*px+u1*qx; ball1.vy = v1f*py+u1*qy; ball2.vx = v2f*px+u2*qx; ball2.vy = v2f*py+u2*qy; } }
Maintained by John Loomis, updated Sun Feb 17 18:43:52 2013