• 13
• 18
• 19
• 27
• 9

# SDL Collision Detecion off

This topic is 2615 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

So I finally figured out what was wrong with my collision. After solving the problem, I decided to add another character, which lead me to another problem. When I load up my game, everything works fine, but as soon as I move, I collide with my other character, who is all the way across the map. I worked at it for hours, and I can't find a solution. I've included my dimensions, collision detection, and the function code where I call collision between my characters. (BTW My map is 1200 by 600)

 //Dimensions A.x = 50; A.y = 65; A.w = 64; A.h = 64; A2.x = 1100; A2.y = 470; A2.w = 64; A2.h = 64; //Collision Detection bool a2_collision( SDL_Rect A, SDL_Rect A2 ) { int leftA, leftA2; int rightA, rightA2; int topA, topA2; int bottomA, bottomA2; leftA = A.x; rightA = A.x + A.w; topA = A.y; bottomA = A.y + A.h; leftA2 = A2.x; rightA2 = A2.x + A2.w; topA2 = A2.y; bottomA2 = A2.y + A2.h; if( bottomA > topA2 ) { return true; } if( topA > bottomA2 ) { return true; } if( rightA > leftA2 ) { return true; } if( leftA > rightA2 ) { return true; } return false; } //function if (a2_collision( A , A2 )) {SDL_WM_SetCaption ("Defender Wins!", NULL); SDL_Delay(3000); done = 1;}  Edited by Kylotan
Changed to use code editor

##### Share on other sites
The function appears to return true if there is no collision, and false if there is a collision. That's the opposite of what I would expect.

##### Share on other sites
As Kylotan alluded to, the logic of the test is wrong. Consider the first conditional:

if (bottomA > topA2) { return true; }
Box A could be somewhere below box A2 and yet not touching it, and this conditional would still (falsely) return true.

Also, note that this isn't really an 'SDL' collision detection problem; it's just a collision detection problem. (The fact that the SDL_Rect structure is being used is incidental and has no bearing on the problem itself.)

 bool HasCollision(const SDL_Rect& a, const SDL_Rect& { return !( /* doesn't intersect horizontally */ (b.x > (a.x + a.w) || (b.x + b.w) < a.x) || /* doesn't intersect vertically */ (b.y > (a.y + a.h) || (b.y + b.h) < a.y) ); }