0
\$\begingroup\$

I am currently trying to make a Mario-type platformer using pygame and the MVC design pattern. My progress as of right now is getting a character on screen and having it move left and right.

My goal is to have this character have the ability to jump when spacebar is pressed. It is definitely recognizing that spacebar is pressed, but the character just stops in place instead of jumping. Here is the code for the character that I currently have:

import pygame


class Player(pygame.sprite.Sprite):
    def __init__(self, name, x, y, img_file):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.image.load(img_file).convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.falling = True
        self.onGround = False
        self.v = 0
        self.speed = 2

    def moveLeft(self):
        self.rect.x -= self.speed
    def moveRight(self):
        self.rect.x += self.speed
    def jump(self):
        if self.onGround == False:
            return
        self.velocity = 8
        self.onGround = False

and here is the controller part corresponding to this:

if event.type == pygame.KEYDOWN:
    if(event.key == pygame.K_SPACE):
        self.player.jump()

Thanks

\$\endgroup\$
1
  • \$\begingroup\$ Where is the code that update the player's position? \$\endgroup\$ Commented Nov 16, 2018 at 14:28

2 Answers 2

1
\$\begingroup\$

I have never worked with Pygame, but are you not defining on init self.onGround = false?

    self.falling = True
    self.onGround = False
    self.v = 0

That would mean that if jump is called, nothing happens.

def jump(self):
    if self.onGround == False:
        return
    self.velocity = 8
    self.onGround = False

Maybe there is something else you dont show in your code, but if you dont set onGround to true in the meantime, you can't jump.

\$\endgroup\$
0
\$\begingroup\$

You didn't increased the y-position of the sprite when it is jumping

self.rect.y -= self.velocity

Also, add a gravity function in your game beforehand so that your sprite stopped jumping at some point

def gravity(self):
    if self.vy == 0:
        self.vy = 1
    else:
        self.vy += .45

    if self.rect.y >= (Screen_Height - 5) - self.rect.height and self.vy >= 0:
        self.vy = 0
        self.rect.y = (Screen_Height - 5) - self.rect.height
        self.OnGround = True
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .