Tag Archives: collision detection

[ SDL2 – Part 5 ] Collision detection

Collision detection

Collision detection is one of the key aspects of game programming. For all non-rectangular objects it gets harder and harder the more accurate you want it to be. But today we’re gonna continue just using rectangles. This part describes a simple algorithm to check for intersections.

After we’ve created a functions that does rectangle-rectangle collision detections, we’ll use all of what we’ve learned so far and make a simple game!

Rectangle – rectangle collisions

Instead of checking if two rectangles are inside or touching each other, we’re gonna check for the opposite; if they are outside of each other. The algorithm to do so consists of two steps.

  1. Find the x coordinate of the left and right and the y coordinate for top and bottom.

    Say we have two rectangles, rect1, and rect2.

    Finding the x/y of left/right/top/bottom is very easy.

    The process is exactly the same for the second SDL_Rect.

  2. Use the 8 edges to check if they are not colliding

    Take a look at the drawing below

    As you can see, the red rectangle is farther to the right than the blue one. But how do can we easily check that? Simply by checking if redLeft is further to the right than blueRight. If it is ( like it is in our case ) there is no collision. Then it’s just a simple matter of repeating it for the other edges. So we end up with something like this :

    This is the final function for you to copy and test out.

    If you want to shorten the code, you can remove the comments and replace the variables with the rect. x / y / w / h values like so :

    I chose to not do this as the longer version is a bit easier to read and understand.

Our first game!

Our first game is of the “lead the chicken safely across the road” kind of things. Or, as in our case, “lead the square from the rectangle, past all the other squares and to the other rectangle.” You control the square with the arrow keys. If you hit a red square, you’ll end up where you started. If you make it to the other side, you’ll also end up where you started, but at least you have that tiny sense of victory for helping our poor little square!

The code just uses the different things we’ve learned so far, so I won’t explain it other than in code comments and ( hopefully ) descriptive names.

So without further ado, here’s the code :

Feel free to comment if you have anything to say or ask questions if anything is unclear. I always appreciate getting comments.

You can also email me : olevegard@headerphile.com