Search code examples
pythonpygamecollision-detection

pygame collision with ceiling?


I've only seen information about collisions with walls on here but I'm having a problem making the player "bump" its head on the ceiling. Instead of hitting its head, velocity being set to 0 and it accelerating back down due to gravity, the object gets sucked up ontop of the platform above it. Why isn't this working and how can I fix it? I'm following a tutorial and trailing off to my own adaptation and the content creator said that it would be hard to implement. Apparently there may also be an error if you collide diagonally? (according to the content creator)

Thank you so much in advance, teacher wants me to create something to present infront of people in only a couple of days with no experience with any sort of game engine.

def update(self):
    # Game Loop - Update
    self.all_sprites.update()
    # check if player hits a platform
    hits = pygame.sprite.spritecollide(self.player,self.platforms , False)
    if self.player.vel.y > 0:
        if hits:
            self.player.pos.y = hits[0].rect.top
            self.player.vel.y = 0
    if self.player.vel.y < 0:
        if hits:
            self.player.rect.top = hits[0].rect.bottom
            self.player.vel.y = 0

Solution

  • Instead setting the velocity to 0, you might want to set the velocity to -1 or some other negative value to force movement 'downward' out of the boundary condition. You could also add acceleration if desired in the same condition:

    if hits:
            self.player.pos.y = hits[0].rect.top
            self.player.vel.y = -1  # example velocity
            self.player.acc.y = 2   # example acceleration