Python | Making an object jump in PyGame
Last Updated :
19 Feb, 2020
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit.
So, in this article, we will learn how to make an object jump using PyGame library in Python.
There is basic formula from classical mechanics to make an object jump.
F = 1/2 * m * v^2
Where F is the force up/down, m is the mass of the object and v is the velocity. The velocity goes down over time because when the object jumps the velocity will not increase more in this simulation. When object reaches the ground, the jump ends. If isjump
variable is True or False it indicates object is jumping or not. If isjump
is True, object position will be updated according to the above formula.
Below is the implementation:
import pygame
pygame.init()
win = pygame.display.set_mode(( 500 , 500 ))
pygame.display.set_caption( "Jump Game" )
x = 200
y = 200
width = 30
height = 40
isjump = False
v = 5
m = 1
run = True
while run:
win.fill(( 0 , 0 , 0 ))
pygame.draw.rect(win, ( 255 , 0 , 0 ), (x, y, width, height))
for event in pygame.event.get():
if event. type = = pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if isjump = = False :
if keys[pygame.K_SPACE]:
isjump = True
if isjump :
F = ( 1 / 2 ) * m * (v * * 2 )
y - = F
v = v - 1
if v< 0 :
m = - 1
if v = = - 6 :
isjump = False
v = 5
m = 1
pygame.time.delay( 10 )
pygame.display.update()
pygame.quit()
|
Output :
Share your thoughts in the comments
Please Login to comment...