Collision For TileMap

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.

1 Like

You’re right, so I’m creating and drawing tiles seperately now, so it’s a bit better. How do you fix player colliding with adjacent tiles?

Hi,

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.

1 Like

Thanks man collision works better now. I can’t jump and I can’t explain why?

GCC with -Wall gives me the following warning:

Game.cpp:148:35: warning: statement has no effect [-Wunused-value]
  speedY += (gravity * collision); - (jumpStr * up);
                                   ^~~~~~~~~~~~~~~~

1 Like

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.

1 Like

AND,

Sorry I overlooked that.

I’m not sure I understand :thinking:

I will modify the collision detection accordingly and update you :+1:

I wasn’t able to do what you told me. Instead I ended up doing something completely different. I hope this fixes the axis problem. Here’s the link.

1 Like

Hey man, the collision problem’s solved for good this time. Thank you for your help!
Did it in a different way but I guess it works, here’s the link

1 Like

Thank you for all your help :smiling_face:

1 Like