Python Forum
can't get collision detection to work in platform game
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
can't get collision detection to work in platform game
#2
You collision detection fails because you pass playerx and playery to move() when you should pass player_speed and player_y_momentum.

move() should look like this:
def move(rect, xstep, ystep, tiles):
    collisions = {'top': False, 'bottom': False, 'right': False, 'left': False}
    # Move in x and check for collisions
    rect.x += xstep
    for tile in tiles:
        if rect.colliderect(tile):
            if xstep > 0:
                collisions['right'] = True
            elif xstep < 0:
                collisions['left'] = True
            break

    # Move in y and check for collisions
    rect.x -= xstep
    rect.y += ystep
    for tile in tiles:
        if ystep > 0:
            collisions['bottom'] = True
        elif ystep < 0:
            collisions['top'] = True
        break
    return collisions
You weren't using the returned rect value, so don't return it. After checking for x collisions you want to move rect back (rect.x -= xstep) otherwise an x collision is also reported as a y collision.

You'll also want to change the code that calls move()
    playery += player_y_momentum
    player_y_momentum = min(3, player_y_momentum + 0.2)
    collisions_type = move(playerrect, player_speed, player_y_momentum , tile_rects)
Reply


Messages In This Thread
RE: can't get collision detection to work in platform game - by deanhystad - Aug-16-2022, 06:21 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question [PyGame] Problem with collision of player and enemy Nekotrooper 1 892 Dec-08-2023, 03:29 PM
Last Post: deanhystad
  [PyGame] Players not falling from the platform, and some other errors. urmom33 1 1,756 Jan-23-2023, 10:28 PM
Last Post: deanhystad
  [PyGame] Collision in not happening onizuka 3 3,538 Sep-07-2020, 11:30 AM
Last Post: metulburr
  [PyGame] No collision detection onizuka 6 3,823 Aug-18-2020, 01:29 PM
Last Post: onizuka
  Problem with collision detection... michael1789 4 3,425 Nov-12-2019, 07:49 PM
Last Post: michael1789
  Arcade Collision Problem randor 0 2,751 Oct-28-2019, 11:17 PM
Last Post: randor
  Multiple wall collision in pacman rustyjoe 4 4,248 Aug-11-2019, 08:08 AM
Last Post: rustyjoe
  drawing, moving, and collision problems (pygame) SheeppOSU 26 15,254 Apr-22-2019, 03:09 AM
Last Post: SheeppOSU
  [PyGame] Game doesn't work after pause Owenix 2 3,248 Sep-20-2018, 08:44 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020