Reputation: 47
I am trying to make the player sprite stop falling on the platform rect top. I have tried a lot of things over the past two days and I am more lost then I've ever been. Thank you so much. I am using tmx to load a tiled map. I add a Platform object every the name is detected and than I add that to a list. I enumerate through the list to check collision using sprite.collide(self.player, plat). This doesn't work.
def update(self):
for plat in self.platList:
self.hits = pg.sprite.spritecollide(self.player,self.platList,False)
if self.hits:
if self.player.pos.y > self.hits[0].y:
self.player.pos.y = self.hits[0].rect.top
for tile in self.map.tmxdata.objects:
if tile.name == "player":
self.player = Player(self,tile.x,tile.y)
if tile.name == "Platform":
self.platList.append(Platform(self, tile.x, tile.y,tile.width,tile.height))
class Platform(pg.sprite.Sprite):
def __init__(self,game,x,y,width,height):
self.game = game
pg.sprite.Sprite.__init__(self)
self.rect = pg.Rect(x,y,width,height)
self.y = y
self.rect.x = x
self.rect.y = y
Upvotes: 1
Views: 215
Reputation: 101052
I guess your problem is that you don't use the player's rect
attribute to define the position of the player. You're using pygame's sprites, so use them the way it is intended.
All pygame functions that deal with sprites (e.g. spritecollide
) will use the rect
attribute, but in your code the player class has an additional pos
attribute, and Platform
also has a y
attribute.
Remove them, and use rect
exclusively to store the size and position of your sprites.
When you want to move a sprite, just change its rect
(e.g. with move_ip
etc.) or its attributes.
Upvotes: 2