Advertisement
smhdale

lineIntersectsPolygon

Jul 7th, 2019
871
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const { checkIntersection } = require('line-intersect')
  2.  
  3. const playerLine = [
  4.   { x: 10, y: 10 }, // Player current pos
  5.   { x: 30, y: 10 }  // Player target pos
  6. ]
  7.  
  8. const floorPolygon = [
  9.   { x: 0, y: 0 },
  10.   { x: 20, y: 0 },
  11.   { x: 20, y: 20 },
  12.   { x: 0, y: 20 }
  13. ]
  14.  
  15. function getPointsArr (obj, i) {
  16.   const j = (i + 1) % obj.length
  17.   return [ obj[i].x, obj[i].y, obj[j].x, obj[j].y ]
  18. }
  19.  
  20. function lineIntersectsPolygon (line, polygon) {
  21.   // Convert line to points array
  22.   const linePoints = getPointsArr(line, 0)
  23.  
  24.   // Check each edge of polygon
  25.   for (let i = 0; i < polygon.length; i++) {
  26.     const polyPoints = getPointsArr(polygon, i)
  27.     const { type, point } = checkIntersection(...linePoints, ...polyPoints)
  28.     if (type === 'intersecting') {
  29.       return point
  30.     }
  31.   }
  32.   return false
  33. }
  34.  
  35. console.log(lineIntersectsPolygon(playerLine, floorPolygon))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement