Given the position and dimensions of a square, what is the equation in JavaScript for testing if a line goes through the rectangle?
What I have tried so far is:
function isSquareIntersectingLine(square, line) {
return (
line.startX >= square.topLeftX &&
line.startX <= square.topLeftX + square.width &&
line.endX >= square.topLeftX + square.width
);
}
This works for if the dimensions are:
Square: {topLeftX: 0, topLeftY: 0, width: 5, height: 5}
Line: {startX: 2, startY: -4, endX: 6, endY: 3}
But if the dimensions are like this, it won't work:
Square: {topLeftX: 0, topLeftY: 0, width: 5, height: 5}
Line: {startX: 2, startY: -4, endX: 3, endY: 10}
What is the correct formula for checking if a line segment intersects a square in JavaScript?