Search code examples
pythonpyglet

How to make a sprite jump in Pyglet?


I've been making a personal project to remake a modified version of SUper Mario Bros. So far, I've been able to add in the Mario sprite along with the ground and bricks. Now, I'm stuck with how to make Mario jump. Does anyone know how to do it?

EDIT: I already made a class for Mario, but can't get the jump to work. Any ideas why?

class mario(pyglet.sprite.Sprite):
    def __init__(self, batch):
        self._img_main = pyglet.image.load("Mario_Right.png")

        self.img_right1 = pyglet.image.load("Mario_Walk_Right1.png")
        self.img_right2 = pyglet.image.load("Mario_Walk_Right2.png")
        self.anim_right = pyglet.image.Animation.from_image_sequence([self.img_right1, self.img_right2], 0.5, True)
        pyglet.sprite.Sprite.__init__(self, self._img_main)
        self.time = 0

    def forward_movement(self, flag=True):
        if flag:
            self.image = self.anim_right 
        else:
            self.image = self._img_main
   def jump(self,flag=True):
        print time.time()-self.time
        self.y -= -10 +20**(time.time()-self.time+.2)

    def on_key_press(self, symbol, modifiers):
        self.keys_held.append(symbol)
        if symbol == pyglet.window.key.RIGHT:
            self.player.forward_movement(True)
        if symbol == pyglet.window.key.LEFT:
            self.player.time=time.time()
            self.player.jump()

Solution

  • Try to create gravity on your code. First, create a class for your Mario. Set up their positions and speed. Put up method jump on your Mario.

    #put this in your init
    self.time = 0
    
    #put this in your condition
    if keymap[pyglet.window.key.RIGHT]:
        self.mario.time = time.time()
        self.mario.jump()
    
    def jump(self):
        print time.time()-self.time
        self.y -= -10 +20**(time.time()-self.time+.2)