42 lines
1.6 KiB
Plaintext
42 lines
1.6 KiB
Plaintext
// https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line_segment
|
|
PVector intersect(PVector A, PVector B, PVector C, PVector D) {
|
|
final float d = ((A.x-B.x)*(C.y-D.y)-(A.y-B.y)*(C.x-D.x));
|
|
final float t = ((A.x-C.x)*(C.y-D.y)-(A.y-C.y)*(C.x-D.x))/d;
|
|
final float u = ((A.x-C.x)*(A.y-B.y)-(A.y-C.y)*(A.x-B.x))/d;
|
|
PVector output = null;
|
|
if (0 <= t && t <= 1 && 0 <= u && u <= 1)
|
|
output = new PVector(A.x+t*(B.x-A.x), A.y+t*(B.y-A.y));
|
|
return output;
|
|
}
|
|
|
|
// https://math.stackexchange.com/questions/65503/point-reflection-over-a-line
|
|
void reflect(Projectile p, Wall w) {
|
|
// Position -> Next : A -> B
|
|
// Wall.start -> Wall.end : C -> D
|
|
final PVector A = p.position.copy();
|
|
final PVector B = p.next.copy();
|
|
final PVector C = w.start.copy();
|
|
final PVector D = w.end.copy();
|
|
final PVector I = intersect(A, B, C, D);
|
|
|
|
if (I != null) {
|
|
// Calculating E, which is reflecting Point B across line CD
|
|
final float dx = D.x - C.x;
|
|
final float dy = D.y - C.y;
|
|
final float at = (dx * dx - dy * dy) / (dx * dx + dy*dy);
|
|
final float bt = 2 * dx * dy / (dx*dx + dy*dy);
|
|
PVector E = new PVector(
|
|
at * (B.x - C.x) + bt*(B.y - C.y) + C.x,
|
|
bt * (B.x - C.x) - at*(B.y - C.y) + C.y
|
|
);
|
|
|
|
// Calculate E, such that Lines AI and IE are of the same length
|
|
E.sub(I).setMag(PVector.dist(I, A)).add(I);
|
|
|
|
p.next = E.copy();
|
|
PVector newVelocity = PVector.sub(E, I);
|
|
newVelocity.setMag(p.velocity.mag());
|
|
p.velocity = newVelocity.copy();
|
|
}
|
|
}
|