1

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
  • In future, remember to [format your code correctly](https://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks). At the moment your code is not properly indented. – Micheal O'Dwyer Jan 29 '18 at 15:28
  • Please show us a [minimal, complete and verifiable example](https://stackoverflow.com/help/mcve) and describe your goals and problems as clearly as possible, otherwise we can't give you a definitive answer and you'll only get guessed and maybe misleading answers. – skrx Jan 29 '18 at 21:15

1 Answers1

2

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.

sloth
  • 99,095
  • 21
  • 171
  • 219