-1

I'm trying to make a platformer game and I want to make a rule to where the player can only jump when the player is colliding with a platform rectangle's top side.

I've tried the following:

First, just seeing if the y-direction is 0 (thus no movement): if keys[pygame.K_w] and self.direction.y == 0: self.jump()

But, this leads to you being able to hover above the ground granted your 'head'(the self.rect.top) can hit the underside of a platform (in which the collision function would kick in and set the y-direction to 0)

My next thought would to be using: if keys[pygame.K_w] and self.rect.collidelist(platform_list): self.jump() where platform_list is a list of rectangles, i.e. <rect(0, 0, 64, 64)>, <rect(64, 0, 64, 64)>, etc. This doesn't seem to have any effect, as I am able to spam the jump button.

Any help would be much appreciated!

Rabbid76
  • 202,892
  • 27
  • 131
  • 174

1 Answers1

-1

Perhaps take a look at this question: rect collision with list of rects. There are a few ways of doing this. You could use a for loop:

collision = False
for platform in platform_list:
    if player_rect.colliderect(platform):
         collision = True
if not collision:
    self.jump()

But I believe this would be more efficient:

if player_rect.collidelist(tile_rects) >= 0:
    self.jump()
BitPigeon
  • 1
  • 4
  • I've taken a look at that before, but my main problem is trying to see if it ever collided with the top of a platform rect. I tried implementing this and it did the same as the `if self.direction.y == 0:` I might just have to redesign the collision detection :/ – MrRoboto404 May 13 '23 at 03:10