parallelogram intersection
// Hope you enjoy this little algorithm I made!
// It checks a point to see if it lies in a parallelogram
// With some additional code, can be a collisoin detection algorithm
// Note: this will ONLY work with parallelograms (including rhombi, squares and rectangles)
const collide = (point, shape) => point.y >= shape.y1 && point.y <= shape.y4 && point.x >= (point.y - shape.y1) / ((shape.y4 - shape.y1) / (shape.x4 - shape.x1)) + shape.x1 && point.x <= (point.y - shape.y2) / ((shape.y3 - shape.y2) / (shape.x3 - shape.x2)) + shape.x2;
class Shape {
constructor(x1, y1, x2, y2, x3, y3, x4, y4) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.x3 = x3;
this.y3 = y3;
this.x4 = x4;
this.y4 = y4;
}
draw() {
c.strokeStyle = 'white';
c.beginPath();
c.moveTo(this.x1, this.y1);
c.lineTo(this.x2, this.y2);
c.lineTo(this.x3, this.y3);
c.lineTo(this.x4, this.y4);
c.lineTo(this.x1, this.y1);
c.closePath();
c.stroke();
}
}
const shapes = [];
shapes.push(new Shape(50, 50, 250, 50, 250, 250, 50, 250));
shapes.push(new Shape(100, 100, 200, 100, 250, 200, 150, 200));
const checkCollision = () => {
for (const shape1 of shapes) {
for (const shape2 of shapes) {
if (shape1 != shape2) {
if (
collide({ x: shape1.x1, y: shape1.y1 }, shape2) ||
collide({ x: shape1.x2, y: shape1.y2 }, shape2) ||
collide({ x: shape1.x3, y: shape1.y3 }, shape2) ||
collide({ x: shape1.x4, y: shape1.y4 }, shape2) ||
collide({ x: shape2.x1, y: shape2.y1 }, shape1) ||
collide({ x: shape2.x2, y: shape2.y2 }, shape1) ||
collide({ x: shape2.x3, y: shape2.y3 }, shape1) ||
collide({ x: shape2.x4, y: shape2.y4 }, shape1)) {
canvas.style.background = 'red';
return;
} else canvas.style.background = 'black';
}
}
}
}