#include int check_collision( int r1x, int r1y, int r1w, int r1h, int r2x, int r2y, int r2w, int r2h ) { // First we find out the coordinates of x2 and y2 for both objects. int r1x2 = r1x + r1w; int r1y2 = r1y + r1h; int r2x2 = r2x + r2w; int r2y2 = r2y + r2h; // Next we order the variables left-to-right, top-to-bottom. int o1x1, o1x2, o1y1, o1y2, o2x1, o2x2, o2y1, o2y2; // if( r1x > r1x2 ) { o1x1 = r1x2; o1x2 = r1x; } else { o1x1 = r1x; o1x2 = r1x2; } if( r1y > r1y2 ) { o1y1 = r1y2; o1y2 = r1y; } else { o1y1 = r1y; o1y2 = r1y2; } if( r2x > r2x2 ) { o2x1 = r2x2; o2x2 = r2x; } else { o2x1 = r2x; o2x2 = r2x2; } if( r2y > r2y2 ) { o2y1 = r2y2; o2y2 = r2y; } else { o2y1 = r2y; o2y2 = r2y2; } // // Now we check to see if any of o1's points fall between all of o2's points, and vice-versa. // o1x1, o1y1 if( (( o1x1 >= o2x1 ) && ( o1x1 <= o2x2 )) && (( o1y1 >= o2y1 ) && ( o1y1 <= o2y2 ))) { return 1; } // o1x2, o1y1 if( (( o1x2 >= o2x1 ) && ( o1x2 <= o2x2 )) && (( o1y1 >= o2y1 ) && ( o1y1 <= o2y2 ))) { return 1; } // o1x1, o1y2 if( (( o1x1 >= o2x1 ) && ( o1x1 <= o2x2 )) && (( o1y2 >= o2y1 ) && ( o1y2 <= o2y2 ))) { return 1; } // o1x2, o1y2 if( (( o1x2 >= o2x1 ) && ( o1x2 <= o2x2 )) && (( o1y2 >= o2y1 ) && ( o1y2 <= o2y2 ))) { return 1; } // o2x1, o2y1 if( (( o2x1 >= o1x1 ) && ( o2x1 <= o1x2 )) && (( o2y1 >= o1y1 ) && ( o2y1 <= o1y2 ))) { return 1; } // o2x2, o2y1 if( (( o2x2 >= o1x1 ) && ( o2x2 <= o1x2 )) && (( o2y1 >= o1y1 ) && ( o2y1 <= o1y2 ))) { return 1; } // o2x1, o2y2 if( (( o2x1 >= o1x1 ) && ( o2x1 <= o1x2 )) && (( o2y2 >= o1y1 ) && ( o2y2 <= o1y2 ))) { return 1; } // o2x2, o2y2 if( (( o2x2 >= o1x1 ) && ( o2x2 <= o1x2 )) && (( o2y2 >= o1y1 ) && ( o2y2 <= o1y2 ))) { return 1; } // Next we check to see if o2 is stretched over o1 with none of its points inside o1. // Check a Y-wise overlap of o1 through o2 and the reverse. if( (( o1x1 >= o2x1 ) && ( o1x2 <= o2x2 )) && (( o1y1 <= o2y1 ) && ( o1y2 >= o2y2 ))) { return 1; } if( (( o2x1 >= o1x1 ) && ( o2x2 <= o1x2 )) && (( o2y1 <= o1y1 ) && ( o2y2 >= o1y2 ))) { return 1; } // Guess there's no collision. return 0; } using namespace std; // And the test case. int main( int argv, char** argc ) { if( check_collision( 4, 4, 7, 3, 5, 6, 4, 5 ) ) { cout << "test 1 collides" << endl; } if( check_collision( 2, 2, 2, 3, 7, 9, 3, 4 ) ) { cout << "test 2 collides" << endl; } if( check_collision( 2, -3, 6, -9, -5, -7, 10, 15 ) ) { cout << "test 3 collides" << endl; } if( check_collision( -3, -1, 2, 10, -5, 3, 7, 2 ) ) { cout << "test 4 collides" << endl; } return 0; }