I am learning pygame module by developing a platform game.
I am taking inspiration from this Youtube video and channel
I can handle the fact that the player cannot jump if it is not laying on a platform.
But I figured out that when I press the left or right key and jump key at the same time the jump value is twice than what it should be.
I have a class Game
which handle the main game loop and two other sprite classes Player
and Platform
.
Game
In the class Game
I have a method update
in which I am checking the collision between platforms and player.
class Game:
# game main loop
def __init__(self):
# ...
self.hits = None
# ...
def update(self):
# update all sprites in the sprites group
self.all_sprites.update(self.all_events, self.hits)
# check collision between player and platforms
self.hits = pygame.sprite.spritecollide(self.player, self.platforms, False)
if self.hits:
self.player.rect.bottom = self.hits[0].rect.top
Player
In the class Player
I am then using the list of collision and jump only if player is in collision with platforms:
class Player(pygame.sprite.Sprite):
# player class
def __init__(self):
#...
def update(self, events, hits):
keystate = pygame.key.get_pressed()
self.move_player(keystate)
self.apply_gravity()
self.jump(keystate, events, hits)
def jump(keystate, events, hits):
for event in events:
if event.type == pygame.KEYDOWN:
if keystate[KEYS[self.player_data["jump"]]] and hits:
self.rect.y -= self.player_data["jumpPower"]
You can find the whole project code on github.
I captured this issue on the animated gif:
Do you have an idea how to solve this strange behavior ?
The issue is that in your jump
method, you don't check whether or not the player pressed the jump button:
event.key == KEYS[self.player_data["jump"]]
But what if any button was pressed and the jump button is being held down ?! This means that if you manage to press two buttons on the same frame, you subtract from your position twice.
To fix, check whether the event is the jump button:
def jump(keystate, events, hits):
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == KEYS[self.player_data["jump"]] and hits:
self.rect.y -= self.player_data["jumpPower"]