python - Collision detection with PyGame -
i have been making 2d platformer using python pygame. has going good, have stumbled accross many problems collision detection. here are:
- you can't go through objects have exact space go through
- you can go through ceiling (very weird)
the code have big , think that, since involves multiple classes, should post on github, here link repository: https://github.com/pta2002/superbros.
but reference, here colliion detection method:
def detectcollisions(self, x1, y1, w1, h1, x2, y2, w2, h2): if x2 + w2 >= x1 >= x2 , y2 + h2 >= y1 >= y2: return 1 elif x2 + w2 >= x1 + w1 >= x2 , y2 + h2 >= y1 >= y2: return 2 elif x2 + w2 >= x1 >= x2 , y2 + h2 >= y1 + h1 >= y2: return 3 elif x2 + w2 >= x1 + w1 >= x2 , y2 + h2 >= y1 + h1 >= y2: return 4 else: return 0
and here update method:
def update(self, gravity, block_list): if self.velocity < 0: self.falling = true collision = 0 blockx, blocky = 0, 0 self.canmoveright = true self.canmoveleft = true block in block_list: collision = self.detectcollisions(self.x, self.y, self.width, self.height, block.x, block.y, block.width, block.height) if not collision == 0: blockx = block.x blocky = block.y break if not collision == 0: if self.falling: self.falling = false self.onground = true self.velocity = 0 self.y = block.y - self.height else: if collision == 2: self.canmoveright = false if collision == 1: self.canmoveleft = false else: self.falling = true self.onground = false if not self.onground: self.velocity += gravity self.y -= self.velocity if (self.canmoveright , self.xvel > 0) or (self.canmoveleft , self.xvel < 0): self.x += self.xvel if self.jumping: if self.onground: self.velocity = 8 self.onground = false if self.cur_image >= self.num_images - 1: self.cur_image = 0 else: self.cur_image += 1
get familiar pygame.rect, pretty solves problems collision detection if use sprites. (https://www.pygame.org/docs/ref/rect.html) collide them (method returns true if colliding):
rect.colliderect(otherrect)
Comments
Post a Comment