Seperating Axis Theorem

by polarity

HTML

<canvas id="canvas" width="400" height="400"></canvas>

JavaScript

function sketchProc(p) {
  with(p) {
    size(400, 400);
    frameRate(60);
    // Polygons
    let p1;
    const p2 = [
      [100, 100],
      [200, 143],
      [132, 300],
      [92, 215],
    ];

    // Separating Axis Theorem
    const SAT = function(x, y, x2, y2, pol) {
      const pol1 = pol;
      const pol2 = (pol === p1) ? p2 : p1;
      // Let's convert these points into mx+b
      let m = (y2 - y) / (x2 - x);
      let b = y - x * m;

      // First, we need to see what side of the line our shape is on
      // We can do this by seeing whether the vertices are above or below the line
      let side = -1; // 1 means our shape is below, 0 means our shape is above, -1 means we haven't tested yet
      for (let i = 0; i < pol1.length; i++) {
        if (side > -1) {
          continue;
        }
        let p = pol1[i];
        if ((abs(p[0] - x) < 1 && abs(p[1] - y) < 1) || (abs(p[0] - x2) < 1 && abs(p[1] - y2) < 1)) {
          continue; // We don't want to check points that lie on the line
        }
        side = (p[1] < m * p[0] + b) ? 0 : 1; // Check if point is below line or not
        break;
      }

      // Draw a line
      stroke(0, 100);
      strokeWeight(1);
      line(0, b, width, m * width + b);

      // Now let's go through the points of the other polygon
      for (let i = 0; i < pol2.length; i++) {
        let p = pol2[i];
        if ((side === 0 && p[1] > m * p[0] + b) || (side === 1 && p[1] < m * p[0] + b)) {
          continue;
        }
        return true;
      }
      stroke(0, 0, 255);
      strokeWeight(2);
      line(0, b, width, m * width + b);
      return false;
    };

    p.draw = function() {
      p.background(255);

      p1 = [
        [0, 0],
        [64, -20],
        [91, 35],
        [94, 73],
        [26, 98],
      ];
      for (let i = 0; i < p1.length; i++) {
        p1[i][0] += mouseX + Math.cos(frameCount * 0.05 + i * 20) * 10;
        p1[i][1] += mouseY + Math.sin(frameCount * 0.05 + i * 20) * 10;
     ...