For my application, I have a SVG-drawn rectangle that I am using as a hitbox and I'm looking to make a JavaScript function that returns a boolean of true whenever the hitbox touches another rectangle that has been rotated about its centre by some angle using CSS transformations. I have discovered this code from http://www.inkfood.com/collision-detection-with-svg/:
function intersectRect(r1, r2) {
var r1 = r1.getBoundingClientRect(); //BOUNDING BOX OF THE FIRST OBJECT
var r2 = r2.getBoundingClientRect(); //BOUNDING BOX OF THE SECOND OBJECT
//CHECK IF THE TWO BOUNDING BOXES OVERLAP
return !(r2.left > r1.right ||
r2.right < r1.left ||
r2.top > r1.bottom ||
r2.bottom < r1.top);
}
This works great for regular rectangles, but I am unsure how to build upon this to work with my rotated rectangle. When I inspect the rotated rectangle using developer tools in my web browser, I can see that it highlights the rectangle correctly. That being said, when I try to extract the bounding client rectangle using JavaScript, it returns the dimensions of the rectangle in its unrotated form. My question is how do I receive the correct dimensions for my rotated rectangle so I can detect when it collides with my hitbox rectangle? Is there another method for me to detect when my hitbox touches my rotated rectangle? Any help would be much appreciated.
canvas
instead, you're probably going to have an easier time.isPointInPath
in particular may save you a lot of headaches: w3schools.com/tags/canvas_ispointinpath.asp – jmcgrizrect
androtate
methods – jmcgriz