pygame sprite wall collision

后端 未结 3 1882
北恋
北恋 2020-11-28 16:13

I am working on a platform game in python and pygame. The entire code can be found at \"https://github.com/C-Kimber/FBLA_Game\". The issue I am having is with the collision

3条回答
  •  我在风中等你
    2020-11-28 16:59

    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.

提交回复
热议问题