1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
bool Outside(SDL_Rect A, SDL_Rect B)
{
return ( A.x + A.w <= B.x or A.x >= B.x + B.w || A.y >= B.y + B.h or A.y + A.h <= B.y );
}
//CD is short for Collision Detection
enum CD{ A_above_B = 0, A_below_B = 1, A_left_of_B = 2, A_right_of_B = 3 };
struct CD_Info
{
bool Detected;
SDL_Rect* A; SDL_Rect* B; ///The two colliding rects
CD Identifier;
};
CD_Info CollisionDetection( vector<SDL_Rect> *A, vector<SDL_Rect> *B )
{
CD_Info Return = { false, NULL, NULL };
for ( int MemberA = 0; MemberA < A->size(); MemberA++ )
{
if ( Return.Detected )
continue;
int TopA = (*A)[MemberA].y;
int LeftA = (*A)[MemberA].x;
int RightA = (*A)[MemberA].x + (*A)[MemberA].w;
int BottomA = (*A)[MemberA].y + (*A)[MemberA].h;
for ( int MemberB = 0; MemberB < B->size(); MemberB++ )
{
if ( Return.Detected )
continue;
int TopB = (*B)[MemberB].y;
int LeftB = (*B)[MemberB].x;
int RightB = (*B)[MemberB].x + (*B)[MemberB].w;
int BottomB = (*B)[MemberB].y + (*B)[MemberB].h;
/** Wasn't working properly
if ( TopA < BottomB and TopA > TopB )
Return = { true, &(*A)[MemberA], &(*B)[MemberB], A_below_B };
else if ( BottomA < BottomB and BottomA > TopB )
Return = { true, &(*A)[MemberA], &(*B)[MemberB], A_above_B };
else if ( LeftA > LeftB and LeftA < RightB )
Return = { true, &(*A)[MemberA], &(*B)[MemberB], A_left_of_B };
else if ( RightA > LeftB and RightA < RightB )
Return = { true, &(*A)[MemberA], &(*B)[MemberB], A_right_of_B };
/**/
/**/
if ( !Outside( (*A)[MemberA],(*B)[MemberB] ) and fabs(BottomA - BottomB) <= 4 )
Return = { true, &(*A)[MemberA], &(*B)[MemberB], A_left_of_B /* Just a placeholder*/ };
/**/
}
}
return Return;
}
|