../
By Jumping, Falling And Gravity In Pygame
Gravity
- gravity is not a linear function it’s a exponential function
- The longer you fall the faster you fall(exponential)
Process
- gravity += somevalue –> Gravity variable that increases constantly
- 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)
Tags: /python/ /python3/ /pygame/ /gamedev/ /tutorial/ /animation/