Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast rectangle to rectangle intersection

What's a fast way to test if 2 rectangles are intersecting?


A search on the internet came up with this one-liner (WOOT!), but I don't understand how to write it in Javascript, it seems to be written in an ancient form of C++.

struct {     LONG    left;     LONG    top;     LONG    right;     LONG    bottom; } RECT;   bool IntersectRect(const RECT * r1, const RECT * r2) {     return ! ( r2->left > r1->right         || r2->right < r1->left         || r2->top > r1->bottom         || r2->bottom < r1->top         ); } 
like image 585
Robin Rodricks Avatar asked May 02 '10 03:05

Robin Rodricks


People also ask

How do you find the point of intersection of two rectangles?

In order to check that two rectangles intersect all that's needed is x1 < x4 && x3 < x2 && y1 < y4 && y3 < y2 . That's it.

How do you find the intersection of two rectangles in Java?

Rectangle rect1 = new Rectangle(100, 100, 200, 240); Rectangle rect2 = new Rectangle(120, 80, 80, 120); Rectangle intersection = rect1. intersection(rect2); To use java. awt.

How do you find overlap?

At the end of the exhaust stroke and the beginning of the intake stroke both the intake and exhaust valves are open at the same time. This period of time (in degrees) is know as the Overlap Period.


1 Answers

This is how that code can be translated to JavaScript. Note that there is a typo in your code, and in that of the article, as the comments have suggested. Specifically r2->right left should be r2->right < r1->left and r2->bottom top should be r2->bottom < r1->top for the function to work.

function intersectRect(r1, r2) {   return !(r2.left > r1.right ||             r2.right < r1.left ||             r2.top > r1.bottom ||            r2.bottom < r1.top); } 

Test case:

var rectA = {   left:   10,   top:    10,   right:  30,   bottom: 30 };  var rectB = {   left:   20,   top:    20,   right:  50,   bottom: 50 };  var rectC = {   left:   70,   top:    70,   right:  90,   bottom: 90 };  intersectRect(rectA, rectB);  // returns true intersectRect(rectA, rectC);  // returns false 
like image 85
Daniel Vassallo Avatar answered Oct 09 '22 15:10

Daniel Vassallo