Jumping, Falling And Gravity In Pygame

Vishal Rashmika published on
1 min, 117 words

Categories: Pygame

Gravity

  • gravity is not a linear function it's a exponential function
  • The longer you fall the faster you fall(exponential)

Process

  1. gravity += somevalue --> Gravity variable that increases constantly
  2. palyer.y += gravity --> (The falling rate)
# player falling down with gravity

player_gravity = 0 # global variable

# exponential function
player_gravity += 1
player_rectangle.y += player_gravity

screen.blit(player_surface, player_rectangle)

# player jumping with space and falling with gravity

player_gravity = 0 # global variable

# event loop to jump if the space is pressed
if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                player_gravity = -20
                print("jump")

# event loop to jump if the player is clicked with the mouse
if event.type == pygame.MOUSEBUTTONDOWN:
            if player_rectangle.collidepoint((event.pos)):
                    player_gravity = -20


# exponential function (outside the event loop)
player_gravity += 1
player_rectangle.y += player_gravity

screen.blit(player_surface, player_rectangle)