two rectangles are intersecting in javascript

To check if two rectangles are intersecting in JavaScript, we need to compare the coordinates of each rectangle and check if they overlap. We can do this by comparing the x and y coordinates of the top-left and bottom-right corners of each rectangle. If they overlap, the rectangles are intersecting.

Here's a code snippet that checks for intersection between two rectangles:

index.tsx
function isIntersecting(rect1, rect2) {
  // Check if rect1 intersects rect2
  return rect1.x < rect2.x + rect2.width &&
         rect1.x + rect1.width > rect2.x &&
         rect1.y < rect2.y + rect2.height &&
         rect1.y + rect1.height > rect2.y;
}

// Example usage:
const rect1 = { x: 0, y: 0, width: 50, height: 50 };
const rect2 = { x: 25, y: 25, width: 50, height: 50 };
const isColliding = isIntersecting(rect1, rect2);
console.log(isColliding); // true
466 chars
14 lines

In this example, we define two rectangles using x, y, width, and height properties. We also define the isIntersecting function that takes two rectangle objects as parameters and returns a boolean value indicating whether they intersect or not.

We then use the function to check if rect1 and rect2 intersect by calling isIntersecting(rect1, rect2) and storing the result in the isColliding variable. The console output is true because the two rectangles overlap.

gistlibby LogSnag