• Create Account

## How to do Collision Checking in SDL?

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

13 replies to this topic

### #1DarkHorseKnight  Members

Posted 18 January 2012 - 01:12 PM

Hello I've been wondering for about a day now how to do Collision checking in SDL I tried lazy foo tutorial but got an idea of it but I still don't understand how to make it work so if anyone could give me coding hand here is my code tell me if I'm doing something wrong here



//Check Collision Function
bool Check_Collision(SDL_Rect A, SDL_Rect B)
{
//the sides of the rectangle
int leftA, leftB;
int rightA, rightB;
int topA, topB;
int bottomA, bottomB;
//calculate the sides of rect a
leftA = A.x;
rightA = A.x + A.w;
topA = A.y;
bottomA = A.y +A.h;
//Calculate the sides of Rect b
leftB = B.x;
rightB = B.x + B.w;
topB = B.y;
bottomB = B.y + B.h;
if( bottomA <= topB)
{
return false;
}
if( topA >= bottomB)
{
return false;
}
if( rightA <= leftB)
{
return false;
}
if(leftA >= rightB)
{
return false;
}
return true;
}

while(Check_Collision(MarioRect,GroundOneRect))
{
MarioRect.y -= 7;
}



This should work I would have thought but it doesn't move the MarioRect image anywhere it just carrys on its original movement : (

any tips or helps would be nice thanks

### #2Domiii  Members

Posted 18 January 2012 - 02:19 PM

First of all: Make sure that (x, y) of a rectangle is always it's lowest point.
Secondly: I am not even quite sure what the function is supposed to return - It returns true if there is no collision?
Thirdly: Draw a picture! You somehow need to approach your problem analytically. Whenever you do geometrical problems like this, you can easily verify your algorithm if you draw the different cases on a piece of paper.

Now to your code: If you follow suggestion number #3, you will very quickly find out that you cannot make any decision after only looking at a single side. The earliest you can place any return is after you checked against all cases in one dimension.
For example, your code says: "If the bottom of A is beneath top B, we have (or we don't have, I don't know what you are looking for) a collision". But I can think of two different cases where in one case, they collide (topA > bottomB) and another where they don't (topA < bottomB).

Draw the picture and consider all the cases, and you will quickly be able to fix the code by reordering/merging the four checks.

### #3CryoGenesis  Members

Posted 18 January 2012 - 02:26 PM

Hello, Just want to say something about the way you are doing your Collision Detection.

Lets take the first if for example:

if( bottomA <= topB)
{
return false;
}


Now lets say the the Y position of a is 10 and the y Pos of B is 40
if the height of A is 20 (for example) the program will think there is a collision when there is no collision.

A way I would do it is give the rectangle nodes (points) and a separate integer for the last position.

if (any A nodes are in rectangle B's area){
return false;
}

while(true){

if(checkCollision(mario,Rectangle){
move
}else{
mario.pos = mario.lastpos;
}

mario.lastpos = mario.pos;

}

Not sure to be honest.
Hope it helped!

Gen.

### #4wolfscaptain  Members

Posted 18 January 2012 - 02:37 PM


if (leftA > rightB || rightA < leftB || bottomA > topB || topA < bottomB) {

return false; // no collision

} else {

return true; // collision occured

}



### #5CryoGenesis  Members

Posted 18 January 2012 - 02:40 PM

if (leftA > rightB || rightA < leftB || bottomA > topB || topA < bottomB) {
return false; // no collision
} else {
return true; // collision occured
}


Like I said in my first reply.

This way of doing collision is flawed and does not work.
Due to the fact that even if the rectangles are far from eachother it may return a True.

### #6CryoGenesis  Members

Posted 18 January 2012 - 03:04 PM

Oh and I would definately recommend the book "Killer Game Programming in Java" pretty much goes over stuff like collision, audio, animation, 3d in java, AI.
Although I would only recommend it if you are confident with coding in java.

### #7wolfscaptain  Members

Posted 18 January 2012 - 03:04 PM

if (leftA > rightB || rightA < leftB || bottomA > topB || topA < bottomB) {
return false; // no collision
} else {
return true; // collision occured
}


Like I said in my first reply.

This way of doing collision is flawed and does not work.
Due to the fact that even if the rectangles are far from eachother it may return a True.

Those conditions mean the rectangles are not overlapping in any direction, I don't see how it is flawed (apart from the fact I use it since ever).

If you want correct response, using SAT (google separating axis theorm) is the easiest form of collision response, if not very good in the long term (it's not continouous, so if you have a large velocity compared to your objects, they might go through each other in one frame).

Here's a simple Rectangle-Rectangle SAT test (in JavaScript, but you get the point):
function SAT_solveCollision(a, b) {
var vector = [0, 0];

var left = (b.position[0]) - (a.position[0] + a.size[0]);
var right = (b.position[0] + b.size[0]) - (a.position[0]);
var top = (b.position[1]) - (a.position[1] + a.size[0]);
var bottom = (b.position[1] + b.size[1]) - (a.position[1]);

// this is basically the same conditions as my previous comment but it uses vector projection
if (left > 0 || right < 0 || top > 0 || bottom < 0) {
return vector;
}

if (Math.abs(left) < Math.abs(right)) {
vector[0] = left;
} else {
vector[0] = right;
}

if (Math.abs(top) < Math.abs(bottom)) {
vector[1] = top;
} else {
vector[1] = bottom;
}

if (Math.abs(vector[0]) === Math.abs(vector[1])) {

} else if (Math.abs(vector[0]) < Math.abs(vector[1])) {
vector[1] = 0;
} else {
vector[0] = 0;
}

return vector;
}


This code returns the smallest vector that might get object A out of object B.

Also note that my "origin" of each rectangle is the left-top corner, with the "up" axis pointing down (also known as screen space). If your setup is different, the calculation of left/right/top/bottom will be slightly different.

### #8BeerNutts  Members

Posted 18 January 2012 - 03:16 PM

First of all: Make sure that (x, y) of a rectangle is always it's lowest point.
Secondly: I am not even quite sure what the function is supposed to return - It returns true if there is no collision?
Thirdly: Draw a picture! You somehow need to approach your problem analytically. Whenever you do geometrical problems like this, you can easily verify your algorithm if you draw the different cases on a piece of paper.

Now to your code: If you follow suggestion number #3, you will very quickly find out that you cannot make any decision after only looking at a single side. The earliest you can place any return is after you checked against all cases in one dimension.
For example, your code says: "If the bottom of A is beneath top B, we have (or we don't have, I don't know what you are looking for) a collision". But I can think of two different cases where in one case, they collide (topA > bottomB) and another where they don't (topA < bottomB).

Draw the picture and consider all the cases, and you will quickly be able to fix the code by reordering/merging the four checks.

You're wrong here, and i think it's because you've mis-read the code:

if( bottomA <= topB)
{
return false;
}

What that line says is, if the bottom of RectA is above the Top of Rect B, then there CANNOT be a collision, so return false.

How can that one check NOT guarantee there isn't a collision?
My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

### #9BeerNutts  Members

Posted 18 January 2012 - 03:18 PM

if (leftA > rightB || rightA < leftB || bottomA > topB || topA < bottomB) {
return false; // no collision
} else {
return true; // collision occured
}


Like I said in my first reply.

This way of doing collision is flawed and does not work.
Due to the fact that even if the rectangles are far from eachother it may return a True.

This is the same as the initial code, but cleaner, and will also work. If the rectangles are far away from each other, it will never return true.
My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

### #10CryoGenesis  Members

Posted 18 January 2012 - 03:46 PM

if (leftA > rightB || rightA < leftB || bottomA > topB || topA < bottomB) {
return false; // no collision
} else {
return true; // collision occured
}


Like I said in my first reply.

This way of doing collision is flawed and does not work.
Due to the fact that even if the rectangles are far from eachother it may return a True.

This is the same as the initial code, but cleaner, and will also work. If the rectangles are far away from each other, it will never return true.

Haha sorry, just quickly drew it on paper to better visualise it.
but none the less I still dont think it would work if tested.

### #11CryoGenesis  Members

Posted 18 January 2012 - 03:48 PM

If the rectangles were on the same x axis but something like 1 pixel from being perfectly alligned on the Y axis I do not think this would work..
To tired to test though ;D

### #12DarkHorseKnight  Members

Posted 18 January 2012 - 03:51 PM

Thanks for all the help guys but I'm still not getting the bigger picture here If I draw a rectangle on a piece of paper and then mark out each section of that rectangle like so

|

how would I get it so that my program knows how to intersect and also how to intersect

I had a thought if I could make a big massive picture and basically make a mask of that image like so

That I could then Code it exactly like this probably going to be wrong here but its a guess

int Intersects(SDL_Rect HitBoxRect SDL_Rect ImageRect)
{ //if hitbox exists
if(HitBoxRect)
{

//do a loop that checks for value equality
for(count; count < 1; count++)
{
//they collide
if(HitBoxRect.x  && ImageRect.x = 100)
{
//move image downwards by 1
ImageRect.x -= 1;
}
}
}



is this correct or somewhere near correct I want the simplest method : )

### #13DarkHorseKnight  Members

Posted 18 January 2012 - 06:36 PM

anyone got any ideas?

### #14boogyman19946  Members

Posted 18 January 2012 - 10:52 PM

If you're doing collisions between rectangles, then the separating axis theorem is your best bet.

To quote from http://www.metanetsoftware.com/technique/tutorialA.html#section1 says that if we take two convex shapes and we take their respective projections for all axes then if we can find a single axis where their projections don't overlap, we can be certain that the figures don't overlap either.

To put it in simple terms, we basically take each axis (x and y in this case) and take the coordinate points along that axis of the figure. If you'd like, you can think of it as looking at the "shadow" of the shape on the axis. This way we can check if the figures' shadows overlap on that axis. If they don't, then you're done: these two objects are not overlapping. If the shadows do overlap, then move on to the next axis. If all the axes overlap, then your objects are colliding.

I'd suggest checking out that site for visual pictures and whatnot. They can really help.