Pygame character jump speed problems

Question:

I’m currently trying to make my first game. I am trying to make my character jump, but my code doesn’t have errors but when my character jump it just happens to fast. I don’t know which part to change. I have not been able to figure this out on my own as I am still learning. Here is my code:

import pygame

pygame.init()

screen = pygame.display.set_mode((1200, 600))
WinHeight = 600
WinWidth = 1200

# player
player = pygame.image.load("alien.png")
x = 50
y = 450
vel = 0.3
playerSize = 32

# title
pygame.display.set_caption("First Game")

# Jump
isJump = False
jumpCount = 10

running = True

while running:
    screen.fill((255, 255, 255))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            break
    keys = pygame.key.get_pressed()
    if keys[pygame.K_a] and x > vel:
        x -= vel
    if keys[pygame.K_d] and x < WinWidth - vel - playerSize:
        x += vel
    if not (isJump):
        if keys[pygame.K_w] and y > vel:
            y -= vel
        if keys[pygame.K_s] and y < WinHeight - vel - playerSize:
            y += vel
        if keys[pygame.K_SPACE]:
            isJump = True
    else:
        if jumpCount >= -10:
            neg = 1
            if jumpCount < 0:
                neg = -1
            y -= (jumpCount ** 2) * 0.5 * neg
            jumpCount -= 1
        else:
            isJump = False
            jumpCount = 10
    screen.blit(player, (x, y))

    pygame.display.update()
Asked By: Gabriele

||

Answers:

Use pygame.time.Clock to control the frames per second and thus the game speed.

The method tick() of a pygame.time.Clock object, delays the game in that way, that every iteration of the loop consumes the same period of time. See pygame.time.Clock.tick():

This method should be called once per frame.

That means that the loop:

clock = pygame.time.Clock()
running = True
while running:
    
    clock.tick(60)

    # [...]
Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.