WallSeg.java
public class WallSeg
{
static int count = 0;
Ball pt0, pt1;
String name, str;
double kx, ky, scl;
double q;
WallSeg() {
pt0 = new Ball(250, 200);
pt1 = new Ball(150, 50);
setup();
}
WallSeg(Ball pt1, Ball pt2) {
this.pt0 = pt1;
this.pt1 = pt2;
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;
count++;
name = "wall "+count;
}
public String toString() {
return name;
}
public double dist(Ball ball) {
double px = ball.px - pt0.px;
double py = ball.py - pt0.py;
double dist, radius;
radius = ball.radius;
// distance to line
dist = (kx*py - ky*px);
// distance along line
q = (px*kx+py*ky);
if (q>0 && q<scl) {
return Math.abs(dist)-radius;
}
else if (q<=0) return pt0.dist(ball);
else return pt1.dist(ball);
}
public double intersect(Ball ball) {
double px = ball.px - pt0.px;
double py = ball.py - pt0.py;
double dist, radius, q;
radius = ball.radius;
double tx = 1000.0;
// distance to line
dist = (kx*py - ky*px);
q = (px*kx+py*ky)/scl;
if (q>0 && q<1) {
if (Math.abs(dist)<radius) {
str = String.format("seg violation, dist = %.2f ",dist) + this + " " + ball;
return -2.0;
}
}
// calculate time to intersection
double t;
double vperp = kx*ball.vy - ky*ball.vx;
if (dist<0) {
if (vperp<=0) t=-1.0;
else t = -(radius+dist)/vperp;
}
else {
if (vperp>=0) t=-1.0;
else t = (radius-dist)/vperp;
}
if (t<0.0) return -1.0;
// calculate q at intersection
double qx, qy;
qx = px + ball.vx*t;
qy = py + ball.vy*t;
q = (qx*kx+qy*ky)/scl;
if (q<0 || q>1) return -1.0;
else return t;
}
}
Maintained by John Loomis, updated Sat Mar 03 12:46:22 2018