WallSeg.javaimport java.awt.*;
public class WallSeg
{
Ball pt0, pt1;
Color color;
String str;
double kx, ky, scl;
WallSeg() {
pt0 = new Ball(250, 200);
pt1 = new Ball(150, 50);
color = Color.black;
setup();
}
WallSeg(Ball pt1, Ball pt2) {
this.pt0 = pt1;
this.pt1 = pt2;
color = Color.BLACK;
setup();
}
public void setup()
{
kx = pt1.px-pt0.px;
ky = pt1.py-pt0.py;
scl = Math.hypot(kx,ky);
kx = kx/scl;
ky = ky/scl;
}
public void draw(Graphics g) {
g.setColor(color);
g.drawLine((int)pt0.px,(int)pt0.py,(int)pt1.px,(int)pt1.py);
}
public double intersect(Ball ball, double tstep) {
// distance to pt0
double px = ball.px - pt0.px;
double py = ball.py - pt0.py;
double dist, radius, q;
double d[] = new double[3];
radius = ball.radius;
d[0] = Math.hypot(px,py);
// distance to pt1
double qx = ball.px - pt1.px;
double qy = ball.py - pt1.py;
d[1] = Math.hypot(qx,qy);
// distance to line
d[2] = (kx*py - ky*px);
q = (px*kx+py*ky)/scl;
if (d[2]<0) {
d[0] = -d[0];
d[1] = -d[1];
}
if (q>1) dist = d[1];
else if (q<0) dist = d[0];
else dist = d[2];
str = String.format("dist %6.1f q %6.1f",dist/radius,q);
// calculate time to intersection
double t;
if (q>0 && q<1) {
double vperp = kx*ball.vy - ky*ball.vx;
t = (radius-dist)/vperp;
if (dist<0) t = -(radius+dist)/vperp;
str = str + String.format(" t %6.2f",t);
}
else t = -1;
if (Math.abs(dist)<=radius) ball.color = Color.RED;
else ball.color = Color.YELLOW;
ball.t = t-1;
return t;
}
}
Maintained by John Loomis, updated Wed Nov 13 22:43:10 2013