Reputation: 45
So, i'm trying to make it so when my player collides with a tile in the group self.tiles, and if my player is running at the tile in the right direction, set the player back to the left of that tile. Problem is, i can't use
for tile in self.tiles.sprites():
if tile.rect.colliderect(player.rect):
as, since i also have a vertical collision where it uses the same thing to detect whether a player is standing on it. Only difference between vertical and horizontal, is that the player would collide with two tiles at once in horizontal, so i'd like to see if there's a way to detect if a player touches 2 of the tile sprites in self.tiles.sprites (if there's a more efficient method i'd like to hear it as well)
Upvotes: 1
Views: 94
Reputation: 210909
See pygame.sprite.spritecollide()
:
Return a list containing all Sprites in a Group that intersect with another Sprite.
So if you want to know all the tiles the player collides with, you have to use pygame.sprite.spritecollide()
:
listOfCollindingTiles = pygame.sprite.spritecollide(player, tile, False)
for tile in listOfCollindingTiles:
print(tile.rect)
Another way to handle horizontal and vertical movements and collisions is to perform the horizontal and vertical movements separately:
You can try to separate only the collision detection and the limitation of the players position depending on the movement axis and not the movement itself, however this may not completely solve your problem. It will be a problem if you always fall down slightly, even if you are standing on a tile, so the horizontal collision detection will always detect a collision with the tiles you are standing on.
Your code should look something like this:
# do the horizontal movement here, something like:
# player.rect.x += player.direction.x
collide_x = False
collisioncheck=pygame.sprite.groupcollide(self.player,self.tiles,False,False)
for tile in self.tiles.sprites():
if player.rect.colliderect(tile.rect):
if player.direction.x > 0:
player.rect.right = tile.rect.left
collide_x = True
elif player.direction.x < 0:
player.rect.left = tile.rect.right
collide_x = True
if collide_x:
player.direction.x = 0
# do the vertical movement here, something like:
# player.rect.y += player.direction.y
collide_y = False
collisioncheck=pygame.sprite.groupcollide(self.player,self.tiles,False,False)
for tile in self.tiles.sprites():
if player.rect.colliderect(tile.rect):
if player.direction.y > 0:
player.rect.bottom = tile.rect.top
collide_y = True
elif player.direction.y <= 0:
player.rect.top = tile.rect.bottom
collide_y = True
if collide_y:
player.direction.y = 0
Upvotes: 1