Skip to content Skip to sidebar Skip to footer

Falling Mechanics (gravity) In Pygame

How would I get some mechanics for falling when in an empty space, many answers on the internet said to add gravity but I couldn't understand how they did that they just showed me

Solution 1:

To implement gravity in your game (as in a 2D platformer), you can just increase the y_change variable each frame, so that you move the object a bit faster downwards each time. Take a look at this example:

import pygame as pg


pg.init()

LIGHTBLUE = pg.Color('lightskyblue2')
DARKBLUE = pg.Color(11, 8, 69)

display = pg.display.set_mode((800, 600))
width, height = display.get_size()
clock = pg.time.Clock()

player_image = pg.Surface((30, 60))
player_image.fill(DARKBLUE)

x = width * 0.45
y = 0
x_change = 0
y_change = 0
on_ground = False

# A constant value that you add to the y_change each frame.
GRAVITY = .3

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.KEYDOWN:
            if event.key == pg.K_a:
                x_change = -5
            elif event.key == pg.K_d:
                x_change = 5
            elif event.key == pg.K_s:
                y_change = 5
            elif event.key == pg.K_w:
                if on_ground:  # Only jump if the player is on_ground.
                    y_change = -12
                    on_ground = False
        elif event.type == pg.KEYUP:
            if event.key == pg.K_a and x_change < 0:
                x_change = 0
            elif event.key == pg.K_d and x_change > 0:
                x_change = 0

    # Add the GRAVITY value to y_change, so that
    # the object moves faster each frame.
    y_change += GRAVITY
    x += x_change
    y += y_change
    # Stop the object when it's near the bottom of the screen.
    if y >= height - 130:
        y = height - 130
        y_change = 0
        on_ground = True

    # Draw everything.
    display.fill(LIGHTBLUE)
    pg.draw.line(display, (0, 0, 0), (0, height-70), (width, height-70))
    display.blit(player_image, (x, y))

    pg.display.update()
    clock.tick(60)

pg.quit()

Post a Comment for "Falling Mechanics (gravity) In Pygame"