I'm trying to implement the Seperating Axis Theorem by following this article I found on MDN. Unfortunately, I'm not too geometry savvy and I wasn't able to find any good, simple implementation examples around the internet. I've tried to search for the specific concepts that the article mentions, but I'm not sure that I'm on the right track and I've got several doubts about this.
Here's what I did so far:
export class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
rotate(pivot, angle) {
let s = Math.sin(angle);
let c = Math.cos(angle);
let p = new Point(this.x - pivot.x, this.y - pivot.y);
return new Point((p.x * c - p.y * s) + pivot.x, (p.x * s + p.y * c) + pivot.y);
}
compare(point) {
// todo
}
}
import { Point } from "./Point.js";
export class Line {
constructor(p1, p2) {
this.p1 = p1;
this.p2 = p2;
}
getSlope() {
return (this.p2.y - this.p1.y) / (this.p2.x - this.p1.x);
}
getNormal() {
let dx = this.p2.x - this.p1.x;
let dy = this.p2.y - this.p1.y;
return new Line(new Point(-dy, dx), new Point(dy, -dx));
}
getYIntercept() {
return this.p1.y - this.getSlope() * this.p1.x;
}
getPointProjection(point) {
let slope = this.getSlope();
let yIntercept = this.getYIntercept();
let slope2 = -1 / slope;
let yIntercept2 = point.y - slope2 * point.x;
let nx = (yIntercept2 - yIntercept) / (slope - slope2);
return new Point(nx, (slope2 * nx) + yIntercept);
}
}
import { Point } from "./Point.js";
import { Line } from "./Line.js";
export class Polygon {
constructor(...points) {
this.points = points;
}
overlaps(polygon) {
let side = new Line(this.points[0], this.points[1]);
let axis = side.getNormal();
function findMinAndMaxProjectedPoints(polygon) {
polygon.points.forEach(point => {
let projection = axis.getPointProjection(point);
});
}
}
}
- Did I implement the various formulas correctly?
- How should I "keep track of the highest and lowest values" for each polygon? How am I supposed to determine which projected points are the lowest and which are the highest?
- How do I check for gaps between the highest and lowest projected point of the two polygons?