Collision.java
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 Mon Nov 11 16:00:25 2013