TechieDoggo
TechieDoggo

Reputation: 11

I am not sure how I add gravity to my game?

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)

Upvotes: 1

Views: 53

Answers (1)

Rabbid76
Rabbid76

Reputation: 210876

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()

Upvotes: 1

Related Questions