I am working on a platform game in python and pygame. The entire code can be found at "https://github.com/C-Kimber/FBLA_Game". The issue I am having is with the collision between the player sprite and wall sprites, specifically the corners. When the player is pressing a x movement key and they jump, the player either does not move, or gets stuck. Here is the collision sample:
def wallCollisions(self):
block_hit_list = pygame.sprite.spritecollide(self, self.walls, False)
for block in block_hit_list:
if self.rect.bottom >= block.rect.top and self.rect.bottom <= block.rect.top + 15: # Moving down; Hit the top side of the wall
if self.rect.right > block.rect.left:
self.rect.bottom = block.rect.top
self.yvel = 0
self.onGround = True
self.jumps = 1
elif self.rect.top <= block.rect.bottom and self.rect.top >= block.rect.bottom - 15: # Moving up; Hit the bottom side of the wall
self.rect.top = block.rect.bottom
self.yvel = 0
if self.rect.right >= block.rect.left and self.rect.right <= block.rect.left + 15: # Moving right; Hit the left side of the wall
if self.rect.bottom > block.rect.top+15:
self.rect.right = block.rect.left#+1
self.xvel = 0
elif self.rect.left <= block.rect.right and self.rect.left >= block.rect.right - 15: # Moving left; Hit the right side of the wall
self.rect.left = block.rect.right#-1
self.xvel = 0 = block.rect.right#-1
self.xvel = 0
I've included images on what is happening and what I want.
I have attempted other methods, such as using velocity as determining factos for collision, but this is what is working the best so far. If you could provide a solution it would be greatly appreciated.
Shouldn't
yvel
be set to a positive number to make it go up?The easiest way to handle collisions with walls is to move the player rect or sprite along the x-axis first, check if it collides with a wall and then set its
self.rect.right = wall.rect.left
if it's moving to the right orself.rect.left = wall.rect.right
if it's moving to the left. Afterwards you do the same with the y-axis. You have to do the movement separately, otherwise you wouldn't know the direction and how to reset the position of the rect.Thank you to user sloth! The question he linked gave me some much needed clarity. It took me a bit but I implemented it. I created a function for the collision.
And then I call them in my update function.
The actual useage in my game makes usability near perfect. Not 100% though, this is not a perfect answer.