pygame sprite wall collision [duplicate]

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.

def wallColl(self, xvel, yvel, colliders):
    for collider in colliders:
        if pygame.sprite.collide_rect(self, collider):
            if xvel > 0:
                self.rect.right = collider.rect.left
                self.xvel = 0
            if xvel < 0:
                self.rect.left = collider.rect.right
                self.xvel = 0
            if yvel < 0:
                self.rect.bottom = collider.rect.top
                self.onGround = True
                self.jumps = 3
                self.yvel = 0
            if yvel > 0:
                self.yvel = 0
                self.rect.top = collider.rect.bottom

And then I call them in my update function.

def update(self):
    self.rect.x += self.xvel
    # self.walls is an array of sprites.
    self.wallColl(self.xvel, 0, self.walls) 

    self.rect.y -= self.yvel
    self.onGround = False
    self.wallColl(0, self.yvel, self.walls)

    self.wallCollisions()
    if self.otherplayers != None:
        self.playerCollisions()

    # Gravity
    if self.onGround == False:
        self.yvel-=.0066*self.mass

    self.boundries(highbound, lowbound, leftbound, rightbound)
    self.down = False

The actual useage in my game makes usability near perfect. Not 100% though, this is not a perfect answer.

Leave a Comment