I am learning pygame module developing a platform game. I am taking inspiration from this youtube chanel https://www.youtube.com/watch?v=G8pYfkIajE8.
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 that what it should be. I have a class
Game which handle the main game loop and two other sprite classes
In the class
Game I have a method
update in which I am checking the collision between plaforms 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.rect.top
In the class
Player I am then using the list of collision and jump only if player is in collision with plaforms
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 see on the gif the issue sometimes when I pressed both keys the jump is too high link to example
Do you have an idea how to solve this strange behavior ?
I hope that it is clear enough. You can find the whole project code on github if required https://github.com/pacourbet/platform.git
Many thanks in advance for your help.
The issuse is that in you
jump method, you don’t check whether or not the player pressed the jump button, but 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 wheter 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"]