Buka
Buka

Reputation: 21

How to know if a rectangle collides against a shape such as this?

I have a rectangle and I want to know whether it collides against a shape such as this: https://i.sstatic.net/8RMQZ.png

I've seen algorithms such as this:

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

but that only works if both are rectangles. So how do I figure it out for a rectangle and that shape.

Upvotes: 2

Views: 262

Answers (2)

TravisG
TravisG

Reputation: 2373

You should take a look at algorithms which are based on the "separating-axes-theorem". It's pretty much the standard for fast 2D collision detection, since it's (you could've guessed) very fast (doesn't involve any division or costly operations like sin/cos/sqrt/exp at all) and also works for any possible convex shape (even circles).

Here's an excellent tutorial explaining it: http://www.codezealot.org/archives/55

One thing that makes it so fast is that the algorithm has "early-out" scenarios, where you test one axis and if it doesn't return the desired result, you can exit the entire algorithm knowing that the shapes don't collide.

A nice side effect of the article is that it spits out the smallest possible displacement vector that you need to push your colliding shapes apart.

Upvotes: 0

cnicutar
cnicutar

Reputation: 182609

I don't do this often but you could do it this way:

  • Check if any of the 4 points of the rectangle is inside the polygon
  • Check if any of the (10?) points of the polygon lies inside the rectangle

So this could be reduced to a "point in polygon" problem. Again, it's likely there are better solutions.

Upvotes: 2

Related Questions