Making Sprite Jump in Pygame
There are two things that you should introduce. States and velocity.
In order to make the player fall, we want him to jump only when he is on the ground. So we define 2 states. STANDING
and JUMPING
. Now pressing space would only make the player jump if his state is STANDING
.
To make the player fall like a ball, we introduce velocity
. When the player is on the ground, we have the velocity set to 0. When you press space, you change the velocity to 100.
In each loop, if the player state is JUMPING
, we reduce the velocity
by the Earth's gravity.
The last thing to check, is when the player reaches the ground level, you should set the velocity
to 0 and player state to STANDING
.
Comments
-
Serial almost 2 years
Making a basic game and im trying to get my character to jump when space is pressed
I have a simulated gravity that pulls it down when space is released
but when i push space down it goes up and doesnt stop
i want it to only goo up for like 1 second then go back down
Here is my key press handling code snippet:
key = pygame.key.get_pressed() if key[pygame.K_LEFT]: self.rect.x -= 30 if key[pygame.K_RIGHT]: self.rect.x += 30 if key[pygame.K_SPACE]: self.rect.y += -20 if key[pygame.K_SPACE] == False: self.rect.y += 20
like i said this code makes the sprite go up when space is pressed and down when space is released but when it is pressed i want it to wait one second then make the sprite go back down even if the space bar is still down
Please help!!
thank you