Collision Detection

Hello people! I recently joined the SDL forums! :slight_smile:

I have been toying around with SDL for quite some time now and I’m in a predicament :evil:. For example I move a sprite with the arrow keys (up, down, left, right) at a given speed and I have some rectangles laying around (8 rectangles to be exact). I’m checking the collision between my sprite and the rectangles but the problem is do I loop all the rectangles for collisions whenever I press one key, for example I have a loop at every key press, or do I have one single loop that checks the collisions after the key presses?

I have tested both, the problem I have with the second option is that I can’t get the repositioning of the sprite after colliding correctly, for example when I hold both down and right he moves respectively then the collision occurs. When the collision occurs the new position of the sprite is in the rectangle and the first thing he does depends on the order of the repositioning based and i’m profundly confused lol.

i believe lazy foo has a tutorial on this but from what i generally know is that, you use variables to check which keys are pressed such as bool keys(4) = {0,0,0,0}; array of 4 for each 4 direction then upon pressing/releasing whichever key you set the corresponding array value to either true or false then in your logic portion(which usually comes next from user interaction) is where you update all variable info and check for collisions

You need to keep the direction separate from the keys and then the collision is separate also. As time goes by you’ll get better at breaking things down into these different parts, sort of ‘abstracting’ them from each other, because they are different things. I.e., your key presses affect the direction, which later causes a collision and change in direction as it bounces off or stops. Then when a key is pressed again, the logic has to decide if the sprite can indeed move in that direction because it may be stopped at the edge of a collision and trying to go that way.