0

I am trying to make my character jump. The jumping animation is great, but there is one problem. The rectangle jumps without me pressing the keybind. Also, please make it so the character stops at Y = 260 because that is where I am going to put the ground. (dont come here just to edit my question, actually answer it!) Please help!

import pygame

pygame.init()

win = pygame.display.set_mode((500,300))
pygame.display.set_caption("Run")

y = 100
width = 32
height = 32
jumping = False
jumpVel = 5

run = True

while run:
    pygame.time.delay(100)

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

    keys = pygame.key.get_pressed()

    if keys[pygame.K_SPACE]:
        jumping = True
        
    else:
        if jumpVel >= -10:
            y -= (jumpVel * abs(jumpVel)) * 0.5
            jumpVel -= 1
        else: 
            jumpVel = 10
            jumping = False
    
    win.fill((255,255,255))
    pygame.draw.rect(win, (0,0,0), (128, y, width, height))   
    pygame.display.update() 
    
pygame.quit()
  • You set `jumping = False`, but nowhere in this code do you ever look at the value of `jumping`. I think you're missing an `if` somewhere. – Tim Roberts Mar 09 '22 at 05:39

1 Answers1

0

I recommend reading How to make a character jump in Pygame?.

Just jump if jumping is True. Use the KEYDOWN event for the jump action:

while run:
    # [...]

    or event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygyme.KEYDOWN:
            if not jumping and event.key = pygame.K_SPACE:
                jumping = True
                jumpVel = 10
        
    if jumping and jumpVel >= -10:
        y -= (jumpVel * abs(jumpVel)) * 0.5
        jumpVel -= 1
    else: 
        jumping = False

    # [...]

Note, that pygame.key.get_pressed() returns a sequence with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement.

However, the keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action like jumping or spawning a bullet or a step-by-step movement.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174