# How to do Collision Checking in SDL?

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

## Recommended Posts

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

[CODE]

//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;
}

[/CODE]

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

##### Share on other sites
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.

##### Share on other sites
Hello, Just want to say something about the way you are doing your Collision Detection.

Lets take the first if for example:

[CODE]
if( bottomA <= topB)
{
return false;
}
[/CODE]

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.

##### Share on other sites
[code]
if (leftA > rightB || rightA < leftB || bottomA > topB || topA < bottomB) {
return false; // no collision
} else {
return true; // collision occured
}
[/code]

##### Share on other sites
[quote name='wolfscaptain' timestamp='1326919051' post='4904069']
[code]
if (leftA > rightB || rightA < leftB || bottomA > topB || topA < bottomB) {
return false; // no collision
} else {
return true; // collision occured
}
[/code]
[/quote]

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.

##### Share on other sites
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.

##### Share on other sites
[quote name='CryoGenesis' timestamp='1326919231' post='4904071']
[quote name='wolfscaptain' timestamp='1326919051' post='4904069']
[code]
if (leftA > rightB || rightA < leftB || bottomA > topB || topA < bottomB) {
return false; // no collision
} else {
return true; // collision occured
}
[/code]
[/quote]

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.
[/quote]

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):
[code]
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;
}
[/code]

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.

##### Share on other sites
[quote name='Domiii' timestamp='1326917981' post='4904065']
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.
[/quote]

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

[color=#000088]if[/color][color=#666600]([/color][color=#000000] bottomA [/color][color=#666600]<=[/color][color=#000000] topB[/color][color=#666600])[/color]
[color=#666600]{[/color]
[color=#000088] return[/color][color=#000000] [/color][color=#000088]false[/color][color=#666600];[/color]
[color=#666600]}[/color]

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?

##### Share on other sites
[quote name='CryoGenesis' timestamp='1326919231' post='4904071']
[quote name='wolfscaptain' timestamp='1326919051' post='4904069']
[code]
if (leftA > rightB || rightA < leftB || bottomA > topB || topA < bottomB) {
return false; // no collision
} else {
return true; // collision occured
}
[/code]
[/quote]

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.
[/quote]

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.

##### Share on other sites
[quote name='BeerNutts' timestamp='1326921480' post='4904084']
[quote name='CryoGenesis' timestamp='1326919231' post='4904071']
[quote name='wolfscaptain' timestamp='1326919051' post='4904069']
[code]
if (leftA > rightB || rightA < leftB || bottomA > topB || topA < bottomB) {
return false; // no collision
} else {
return true; // collision occured
}
[/code]
[/quote]

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.
[/quote]

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.
[/quote]

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.

##### Share on other sites
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

##### Share on other sites
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

[img]http://i.imgur.com/4Uh4W.png[/img]|

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

[img]http://i.imgur.com/07wwT.png[/img]

[img]http://i.imgur.com/WkeP5.png[/img]

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

[CODE]
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;
}
}
}

[/CODE]

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

##### Share on other sites
anyone got any ideas?

##### Share on other sites
If you're doing collisions between rectangles, then the separating axis theorem is your best bet.

To quote from [url="http://www.metanetsoftware.com/technique/tutorialA.html#section1"]http://www.metanetsoftware.com/technique/tutorialA.html#section1[/url] 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.

##### Share on other sites

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