Created
December 2, 2015 20:18
-
-
Save emelent/00a3bdc8d920628acb8c to your computer and use it in GitHub Desktop.
Player Jump Sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pygame | |
""" | |
Solution for reddit user found at: | |
https://www.reddit.com/r/pygame/comments/3uw9ja/player_jumps_but_cannot_be_seen_going_upwards/ | |
""" | |
pygame.init() | |
HEIGHT = 360 | |
WIDTH = 480 | |
screen = pygame.display.set_mode((WIDTH, HEIGHT)) | |
GROUND = HEIGHT - 100 | |
BLOCK_DIM = 50 | |
class Block: | |
def __init__(self, x, y): | |
self.image = pygame.Surface((50,50)) | |
self.image.fill((128,0,0)) | |
self.rect = self.image.get_rect() | |
self.rect.x = x | |
self.rect.y = y | |
self.speedx = 0 | |
self.speedy = 0 | |
self.gravity = 3.5 | |
self.jumpvel = 35 | |
def update(self): | |
self.speedx = 0 | |
# self.speedy = 0 #THE LINE WITH THE PROBLEM | |
self.onGround = True | |
keystate = pygame.key.get_pressed() | |
if self.rect.y < GROUND - BLOCK_DIM: | |
self.speedy += self.gravity | |
self.onGround = False | |
elif self.rect.y >= GROUND - BLOCK_DIM: | |
self.speedy = 0 | |
self.onGround = True | |
if keystate[pygame.K_LEFT]: | |
self.speedx = -5 | |
if keystate[pygame.K_RIGHT]: | |
self.speedx = 5 | |
if keystate[pygame.K_UP]: | |
self.jump() | |
self.rect.x += self.speedx | |
self.rect.y += self.speedy | |
def jump(self): | |
if self.onGround == False: | |
return | |
if self.onGround == True: | |
self.speedy -= self.jumpvel | |
def main(): | |
block = Block(40, GROUND - BLOCK_DIM) | |
clock = pygame.time.Clock() | |
while True: | |
clock.tick(50) | |
e = pygame.event.poll() | |
if e.type == pygame.QUIT: | |
break | |
elif e.type == pygame.KEYUP and e.key in [pygame.K_q, pygame.K_ESCAPE]: | |
break | |
screen.fill((255,255,255)) | |
block.update() | |
screen.blit(block.image, block.rect) | |
pygame.display.flip() | |
pygame.quit() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment