I was just looking through some old code and came across something I couldn't quite work out in my head but had to find. Circles was very self explanatory, but rectangular shapes are a bit more awkward, so here's a simple way that will return either a true or false based on the idea that 0 is false and a number greater than 0 is true, assuming rectangle 1 is made of points a and b and rectangle 2 is made of points c and d.

We also assume each point is a list of the [x, y].

That would (more or less) be the gist of detecting if 2 rectangles collide by finding if there is an overlap. The basic idea is make sure all the points are in an area they could be in if there was an overlap. Then by making sure all are in an area they can be in if there is an overlap, detects the overlap, since all must be in those areas for an overlap to exist. For any other shapes that are not square, you must use trigonometry, which I may get into some day down the road.

Points relative to rectangle (showing collision) |

int checkCollision(int a[], int b[], int c[], int d[]) { int c1, c2, c3, c4, c5; c1 = a[0] < d[0]; c2 = a[1] < d[1]; c3 = b[0] > c[0]; c4 = b[1] > c[1]; c5 = c1 && c2 && c3 && c4; return c5; }

That would (more or less) be the gist of detecting if 2 rectangles collide by finding if there is an overlap. The basic idea is make sure all the points are in an area they could be in if there was an overlap. Then by making sure all are in an area they can be in if there is an overlap, detects the overlap, since all must be in those areas for an overlap to exist. For any other shapes that are not square, you must use trigonometry, which I may get into some day down the road.

## No comments:

## Post a Comment