HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Does my Rectangle intersect code work?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
rectangleintersectworkdoescode

Problem

I just want to see if any part of one "rectangle" overlaps the other.
Is this the correct code?

bool checkCollide(int x, int y, int oWidth, int oHeight, int x2, int y2, int o2Width, int o2Height){
    bool collide;
    collide = false;

    if(x >= x2 && x = y2 && y = x2 && x+oWidth = y2 && y = x2 && x= y2 && y+oHeight = x2 && x+oWidth = y2 && y+oHeight <= y2+o2Height){
        collide = true;
    }   
    return collide;
}

Solution

No, this is not correct; it only verifies whether the vertices of one rectangle are inside the other, not the other way around. Try calling it with the following parameters:

checkCollide(2,2,4,4, 1,3,2,2);
checkCollide(1,3,2,2, 2,2,4,4);


They should print the same result, but they don't. This case can be seen in the picture below.

Update: even if you repeat the checks changing x/x2, y/y2, etc, this still won't catch all the cases: two rectangles may intersect even if none of their vertices are inside the other rectangle - see the other picture below.

A more generic solution should use a segment intersection routine to check whether for all segments in one rectangle whether they intersect with any the segments on the other one.

Code Snippets

checkCollide(2,2,4,4, 1,3,2,2);
checkCollide(1,3,2,2, 2,2,4,4);

Context

StackExchange Code Review Q#2533, answer score: 8

Revisions (0)

No revisions yet.