1

I am confused on how I add gravity to my platformer game. I am using pygame for this project. I am relatively new to coding, but anyways here's my code.

import pygame

pygame.init()

win = pygame.display.set_mode((800, 500))
pygame.display.set_caption("Platformer")

x = 200
y = 200

width = 20
height = 20

vel = 5

run = True

FPS = 30
fpsClock = pygame.time.Clock()

while run:

    pygame.time.delay(30)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:

            run = False

    keys = pygame.key.get_pressed()

    if keys[pygame.K_a] and x > 0:

        x -= vel

    if keys[pygame.K_d] and x < 800 - width:

        x += vel

    if keys[pygame.K_w] and y > 0:

        y -= vel

    if keys[pygame.K_s] and y < 500 - height:

        y += vel

    win.fill((0, 0, 0))
    pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
    pygame.display.update()

pygame.display.update()
fpsClock.tick(FPS)

I hope someone can help me get some sort of gravity function working, anything helps. (also what is the best way to make pixelated art, not very relevant to the question)

1 Answers1

1

Gravity just means that the object is moved down a little in each frame:

gravity = 3

while run:
    # [...]

    y += gravity
    if y > win.get_height() - 20:
        y = win.get_height() - 20

I suggest to use a pygame.Rect object to represent the player:

import pygame

pygame.init()
win = pygame.display.set_mode((800, 500))
pygame.display.set_caption("Platformer")

player = pygame.Rect(200, 200, 20, 20)
vel = 5
gravity = 3
run = True
FPS = 30
fpsClock = pygame.time.Clock()
while run:
    fpsClock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()
    player.x += (keys[pygame.K_d] - keys[pygame.K_a]) * vel
    if player.left < 0:
        player.left = 0
    if player.right > win.get_width():
        player.right = win.get_width()

    player.y += gravity
    if player.bottom > win.get_height():
        player.bottom = win.get_height()

    win.fill((0, 0, 0))
    pygame.draw.rect(win, (255, 0, 0), player)
    pygame.display.update()

pygame.quit()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • Alright thanks this helps a lot. By chance could you give me a tip on how I should make the square "jump"? – TechieDoggo Nov 20 '22 at 18:11
  • @TechieDoggo [How to make a character jump in Pygame?](https://stackoverflow.com/questions/70591591/how-to-make-a-character-jump-in-pygame/70591592#70591592) – Rabbid76 Nov 20 '22 at 18:12