Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const { checkIntersection } = require('line-intersect')
- const playerLine = [
- { x: 10, y: 10 }, // Player current pos
- { x: 30, y: 10 } // Player target pos
- ]
- const floorPolygon = [
- { x: 0, y: 0 },
- { x: 20, y: 0 },
- { x: 20, y: 20 },
- { x: 0, y: 20 }
- ]
- function getPointsArr (obj, i) {
- const j = (i + 1) % obj.length
- return [ obj[i].x, obj[i].y, obj[j].x, obj[j].y ]
- }
- function lineIntersectsPolygon (line, polygon) {
- // Convert line to points array
- const linePoints = getPointsArr(line, 0)
- // Check each edge of polygon
- for (let i = 0; i < polygon.length; i++) {
- const polyPoints = getPointsArr(polygon, i)
- const { type, point } = checkIntersection(...linePoints, ...polyPoints)
- if (type === 'intersecting') {
- return point
- }
- }
- return false
- }
- console.log(lineIntersectsPolygon(playerLine, floorPolygon))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement