I'm super new to pygame and I'm trying to get my player to jump smoothly but whenever I press space my player teleports to where they should smoothly move to, but the player smoothly falls down according to the gravity I made.
Here's the block of movement code:
# stop player from falling through the ground
if player.y > HEIGHT - player.height:
player.y = HEIGHT - player.height
# gravity
if player.y != HEIGHT - MAN_HEIGHT:
player.y += GRAVITY
# get player to smoothly jump
if keys_pressed[pygame.K_SPACE]:
if player.y == HEIGHT - MAN_HEIGHT:
if player.y != HEIGHT - MAN_HEIGHT - JUMP_HEIGHT:
player.y -= JUMP_SPEED
Here's all the code in case
# jump from platform to platform
# track height
# platform cannot be taller than half-3/4 jump height
import random
import pygame
import time
WIDTH, HEIGHT = 960, 540 # constants used to set pixels for game
STAGE = pygame.display.set_mode((WIDTH,HEIGHT)) # pass tuple as parameters for .setmode
CLOCK = pygame.time.Clock()
FPS = 60
# starting pos this will start us in the middle left of the screen, hince HEIGHT/2 for y
STARTX = WIDTH / 2
STARTY = HEIGHT / 2
# speeds
PLAYER_SPEED = 8 # how many pixels it will move each time the button is pressed every frame
JUMP_SPEED = 10
JUMP_HEIGHT = 250
GRAVITY = 15
MAN = pygame.image.load('man.png')
MAN_HEIGHT = 147
BG = pygame.image.load('bg.png')
def main():
pygame.init()
player =MAN.get_rect(center=(STARTX,STARTY))
keep_playing = True
while keep_playing:
CLOCK.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
keepPlaying = False
keys_pressed = pygame.key.get_pressed() #this stores every key on the keyboard in a dictionary and a boolean value in the key that says if its pressed or not
if keys_pressed[pygame.K_w]:
player.y -= PLAYER_SPEED
if keys_pressed[pygame.K_s]:
player.y += PLAYER_SPEED
# if player is at screen edge, dont let it go past it
if player.y > HEIGHT - player.height:
player.y = HEIGHT - player.height
# gravity
if player.y != HEIGHT - MAN_HEIGHT:
player.y += GRAVITY
if keys_pressed[pygame.K_SPACE]: # if space pressed
if player.y == HEIGHT - MAN_HEIGHT:
if player.y != HEIGHT - MAN_HEIGHT - JUMP_HEIGHT:
player.y -= JUMP_SPEED
redraw(player)
def redraw(player):
STAGE.blit(BG, (0,0))
STAGE.blit(MAN,(STARTX,player.y)) # using player.y will let us move around
pygame.display.update()
main()
I tried:
if keys_pressed[pygame.K_SPACE]: # if space pressed
if player.y == HEIGHT - MAN_HEIGHT:
if player.y != HEIGHT - MAN_HEIGHT - JUMP_HEIGHT:
for x in range(10):
player.y -= JUMP_SPEED
But this also didn't work.
Also let me know if my code is "ugly" I don't know the conventional methods for making pygame so if I'm making any big mistakes with how I'm doing this please let me know. Thanks!