Skip to content

Latest commit

 

History

History
55 lines (38 loc) · 1.39 KB

File metadata and controls

55 lines (38 loc) · 1.39 KB

If you are Chinese, I suggest you reading this article written by me.

If you are not, okay, it's a case to judge whether the two segments are intersected, vector makes everything simple. Here is a function to decide if two segments are intersected, see below:

/**
 * @param {object} a
 * @param {object} b
 * @return {boolean}
 * a, b stand for two segments
 * (a.x1, a.y1), (a.x2, a.y2) stand for the two point of a; as well as b
 */

function f(a, b) {

  function online(a, b, c) {
    if (a.x >= Math.min(b.x, c.x) && a.x <= Math.max(b.x, c.x) && a.y >= Math.min(b.y, c.y) && a.y <= Math.max(b.y, c.y))
      return true;

    return false;
  }

  var n1, n2, n3, n4;

  n1 = (a.x1 - b.x2) * (b.y1 - b.y2) - (a.y1 - b.y2) * (b.x1 - b.x2);
  n2 = (a.x2 - b.x2) * (b.y1 - b.y2) - (a.y2 - b.y2) * (b.x1 - b.x2);
  n3 = (b.x1 - a.x2) * (a.y1 - a.y2) - (b.y1 - a.y2) * (a.x1 - a.x2);
  n4 = (b.x2 - a.x2) * (a.y1 - a.y2) - (b.y2 - a.y2) * (a.x1 - a.x2);
   
  if (n1 * n2 < 0 && n3 * n4 < 0) 
    return 1;

  var p1 = {x: a.x1, y: a.y1};

  var p2 = {x: a.x2, y: a.y2};

  var p3 = {x: b.x1, y: b.y1};

  var p4 = {x: b.x2, y: b.y2};

  if (n1 === 0 && online(p1, p3, p4))
    return 1;

  if (n2 === 0 && online(p2, p3, p4))
    return 1;

  if (n3 === 0 && online(p3, p1, p2))
    return 1;

  if (n4 === 0 && online(p4, p1, p2))
    return 1;

  return 0;
}