Collision.javapublic class Collision implements Comparable<Collision>
{
double timestep;
Ball ball1, ball2;
int ndx;
Collision(double t, Ball b1, Ball b2)
{
timestep = t;
ball1 = b1;
ball2 = b2;
ndx = -1;
}
Collision(double t, Ball b1, int ndx)
{
timestep = t;
ball1 = b1;
ball2 = null;
this.ndx = ndx;
}
public String toString()
{
String str = "timestep " + timestep;
if (ndx<0) str += " BALL";
else if (ndx==0) str += " PT";
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 (ndx==-1) ball_collision();
else if (ndx==-2) pt_collision();
else wall_collision();
}
// ndx == (2,3) vertical wall, ndx == (0,1) horizontal wall
void wall_collision()
{
if (ndx<2) ball1.vx = -ball1.vx;
else ball1.vy = -ball1.vy;
}
void pt_collision()
{
// relative position
double px = ball1.px - ball2.px;
double py = ball1.py - ball2.py;
// unit vector along line of centers
double vnorm = Math.hypot(px,py);
px = px/vnorm;
py = py/vnorm;
// velocity component (normal)
double v1 = ball1.vx*px+ball1.vy*py;
// velocity component (transverse)
double qx = py;
double qy = -px;
double u1 = ball1.vx*qx+ball1.vy*qy;
// calculate changed velocity
double v1f = -v1;
// back to original coordinates.
ball1.vx = v1f*px+u1*qx;
ball1.vy = v1f*py+u1*qy;
}
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 Wed Nov 13 22:42:55 2013