I’m developing a tile-based game. I encountered some unexpected behaviour in my collision code.
I don’t want to post the whole code here. Because it’s too long and might be painful to read (I am very sorry).
Basically, to detect and resolve collisions, I do this:
pseudocode:
// Resolve horizontal collisions
for tile in tiles:
if checkCollision(tile.rect, player.rect):
match tile.type:
case Empty:
continue
case Platform, Wall:
if player.velocity.x > 0.0:
intersect_rect = calculateIntersection(tile.rect, player.rect)
player.rect.x -= intersect_rect.width
player.velocity.x = 0.0
elif player.velocity.x < 0.0:
intersect_rect = calculateIntersection(tile.rect, player.rect)
player.rect.x += intersect_rect.width
player.velocity.x = 0.0
// Resolve vertical collisions
for tile in tiles:
if checkCollision(tile.rect, player.rect):
match tile.type:
case Empty:
continue
case Platform, Floor:
if player.velocity.y > 0.0:
intersect_rect = calculateIntersection(tile.rect, player.rect)
player.rect.y = tile.rect.y - p.rect.height
player.velocity.y = 0.0
elif player.velocity.y < 0.0:
intersect_rect = calculateIntersection(tile.rect, player.rect)
player.rect.y = tile.rect.y + tile.rect.height
player.velocity.y = 0.0
When I land on top of the platform, I got stuck a little bit, pressing A and D randomly teleport the player to the left side of the platform instantly.
I expect the player to be standing on top of the platform, but still move left and right normally.
I think the issue is the way I handle horizontal collisions, which makes the player’s x velocity become zero and therefore make the player stuck.
Also, I think when my player gets stuck and then I pressed A or D, it will actually push my player back or forward because of those lines: player.rect.x -= intersect_rect.width
and player.rect.x += intersect_rect.width
.
Also, thank you so much for taking time reading my question. This is making me confusing, because I tried adding different checks (only push the player up if he was falling, etc.) but nothing works. I appreciate all your response.