Hello everyone, I’ve came up with collision for a single tile for a single tile and it worked fine. Yesterday I tried making a level basically tried to go from working with a single tile to a collection of tiles and collision started acting weird:
I can’t figure out what the problem is. Here’s the github link
Thank you for your attention.
The create_level function adds a bunch of tiles to the group_of_tiles vector without removing the ones that are already there.
You call create_level inside the render function every frame (don’t you want to call this only once, when the level starts?). This causes the number of tiles to increase as time goes by.
So when you collide with a tile you’re not just colliding with one tile. You are colliding with a whole bunch of tiles. Since you move the player a small distance for each collision that you detect it leads to the player being moved too far. Note that you could run into this problem even without overlapping tiles because the player could collide with two adjacent tiles.
I saw the code and appear when the player collides it not overlap just with one tile, but with two, and so the speedY is decreasing not only once, but twice.
That happens when one first collision is deteted, the for continue to search and found the second collision, and happens the twice sub of speedY.
If you put a break at the end of the if (SDL_IntersectRect()) it will works, and so, just one collision is processed instead of two.
That happens because the line 148 (apoited by @Peter87 ) has a semi-colon inside the expression.
If you remove it, so the jump will works.
But just a little consideration:
You will stay with another bug on the collision. When the player moves at X and Y, the code will not knows what axis to move the player outside the tile. To solve this, it needs to process colision for each axis, for example: when move at X, so check collision, and afetr, when move at Y, check collision.