Basically, I'm trying to create a generic way to check if two shapes are colliding.
I think this is kind of a "double-dispatch" problem, but I'm unsure if there is a better way to solve it in Typescript / Javascript. This is the best I could come up with. Just assume the static helper functions are defined.
abstract class Shape {
abstract collidesWith(shape: Shape): boolean;
}
class Circle extends Shape {
constructor(public x = 0, public y = 0, public r = 0) {
super();
}
collidesWith(shape: Shape) {
let circle = shape as Circle;
if (circle instanceof Circle) {
return Helpers.circlesCollide(this.x, this.y, this.r, circle.x, circle.y, circle.r);
}
let line = shape as LineSegment;
if (line instanceof LineSegment) {
return Helpers.lineIntersectsCircle(line.sX, line.sY, line.eX, line.eY, this.x, this.y, this.r);
}
return false;
}
}
class LineSegment extends Shape {
constructor(public sX = 0, public sY = 0, public eX = 0, public eY = 0) {
super();
}
collidesWith(shape: Shape) {
let line = shape as LineSegment;
if (line instanceof LineSegment) {
return Helpers.lineSegmentsIntersect(this.sX, this.sY, this.eX, this.eY, line.sX, line.sY, line.eX, line.eY);
}
let circle = shape as Circle;
if (circle instanceof Circle) {
return Helpers.lineIntersectsCircle(this.sX, this.sY, this.eX, this.eY, circle.x, circle.y, circle.r);
}
return false;
}
}
I don't really like this solution because there is a decent amount of code-duplication between all the classes. Imagine once rectangles and lines are added. Then again, I also want it to be as performant as possible. Any ideas on how to reduce the repetitiveness of this or increase the performance? Not really a fan of having to use instanceof
and casting all over the place.