Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I have been making a 2d platformer using Python with PyGame. It has all be going good, but I have stumbled accross many problems with collision detection. Here they are:

  1. You can't go through objects that have the exact space for you to go through
  2. You can go through the ceiling (very weird)

The code I have is very big and I think that, since it involves multiple classes, I should post it on GitHub, so here is the link to my repository: https://github.com/pta2002/SuperBros.

But just for reference, here is my colliion detection method:

def detectCollisions(self, x1, y1, w1, h1, x2, y2, w2, h2):

    if x2 + w2 >= x1 >= x2 and y2 + h2 >= y1 >= y2:
        return 1

    elif x2 + w2 >= x1 + w1 >= x2 and y2 + h2 >= y1 >= y2:
        return 2

    elif x2 + w2 >= x1 >= x2 and y2 + h2 >= y1 + h1 >= y2:
        return 3

    elif x2 + w2 >= x1 + w1 >= x2 and y2 + h2 >= y1 + h1 >= y2:
        return 4

    else:
        return 0

and here is my 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

    for 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 and self.xvel > 0) or (self.canMoveLeft and 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
share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.