intersect.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.intersect = exports.IntersectUtils = void 0;
  4. var tslib_1 = require("tslib");
  5. var bounds_1 = require("./bounds");
  6. /**
  7. * Detect whether line-line collision.
  8. * From: https://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
  9. */
  10. function lineToLine(line1, line2) {
  11. var _a = tslib_1.__read(line1, 4), x0 = _a[0], y0 = _a[1], x1 = _a[2], y1 = _a[3];
  12. var _b = tslib_1.__read(line2, 4), x2 = _b[0], y2 = _b[1], x3 = _b[2], y3 = _b[3];
  13. var s10x = x1 - x0;
  14. var s10y = y1 - y0;
  15. var s32x = x3 - x2;
  16. var s32y = y3 - y2;
  17. var denom = s10x * s32y - s32x * s10y;
  18. if (denom === 0)
  19. return false;
  20. var denomPositive = denom > 0;
  21. var s02x = x0 - x2;
  22. var s02y = y0 - y2;
  23. var sNum = s10x * s02y - s10y * s02x;
  24. if (sNum < 0 === denomPositive)
  25. return false;
  26. var tNum = s32x * s02y - s32y * s02x;
  27. if (tNum < 0 === denomPositive)
  28. return false;
  29. if (sNum > denom === denomPositive || tNum > denom === denomPositive)
  30. return false;
  31. return true;
  32. }
  33. function intersectBoxLine(box /** 八个顶点 */, line) {
  34. var lines = [
  35. [box[0], box[1], box[2], box[3]],
  36. [box[2], box[3], box[4], box[5]],
  37. [box[4], box[5], box[6], box[7]],
  38. [box[6], box[7], box[0], box[1]],
  39. ];
  40. return lines.some(function (boxLine) { return lineToLine(line, boxLine); });
  41. }
  42. exports.IntersectUtils = { lineToLine: lineToLine, intersectBoxLine: intersectBoxLine, getBounds: bounds_1.getBounds };
  43. /**
  44. * 检测两个 DisplayObject 是否相交
  45. */
  46. function intersect(a, b, margin) {
  47. var e_1, _a;
  48. var p = (0, bounds_1.getBounds)(a, margin).flat(1);
  49. var q = (0, bounds_1.getBounds)(b, margin).flat(1);
  50. var linesP = [
  51. [p[0], p[1], p[2], p[3]],
  52. [p[0], p[1], p[4], p[5]],
  53. [p[4], p[5], p[6], p[7]],
  54. [p[2], p[3], p[6], p[7]],
  55. ];
  56. try {
  57. for (var linesP_1 = tslib_1.__values(linesP), linesP_1_1 = linesP_1.next(); !linesP_1_1.done; linesP_1_1 = linesP_1.next()) {
  58. var line = linesP_1_1.value;
  59. if (intersectBoxLine(q, line))
  60. return true;
  61. }
  62. }
  63. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  64. finally {
  65. try {
  66. if (linesP_1_1 && !linesP_1_1.done && (_a = linesP_1.return)) _a.call(linesP_1);
  67. }
  68. finally { if (e_1) throw e_1.error; }
  69. }
  70. return false;
  71. }
  72. exports.intersect = intersect;
  73. //# sourceMappingURL=intersect.js.map