Pygame 中实现跳跃

在本文中,你将学习如何在 Pygame 中实现跳跃的逻辑。

移动

左右移动类似于以前的教程,只是意味着改变玩家的 (X,Y) 的位置。对于跳跃,我们使用经典力学的公式:

F = 1/2 * m * v^2

其中 F 是方向上/下的力,m 是物体的质量,v 是速度。速度随着时间的推移而下降,因为当玩家跳跃时,速度在此模拟中不会增加更多。如果玩家到达地面,则跳跃结束。在 Python 中,我们设置一个变量 isjump 来显示玩家是否跳跃。如果是玩家,其位置将根据上述公式进行更新。

完整代码:

from pygame.locals import *
import pygame
import math
from time import sleep
 
class Player:
    x = 10
    y = 500
    speed = 10
 
    # Stores if player is jumping or not.
    isjump = 0     
 
    # Force (v) up and mass m.
    v = 8 
    m = 2
 
    def moveRight(self):
        self.x = self.x + self.speed
 
    def moveLeft(self):
        self.x = self.x - self.speed
 
    def jump(self):
        self.isjump = 1
 
    def update(self):
        if self.isjump:
            # Calculate force (F). F = 0.5 * mass * velocity^2.
            if self.v > 0:
                F = ( 0.5 * self.m * (self.v*self.v) )
            else:
                F = -( 0.5 * self.m * (self.v*self.v) )
 
            # Change position
            self.y = self.y - F
 
            # Change velocity
            self.v = self.v - 1
 
            # If ground is reached, reset variables.
            if self.y >= 500:
                self.y = 500
                self.isjump = 0
                self.v = 8              
 
 
class App:
 
    windowWidth = 800
    windowHeight = 600
    player = 0
 
    def __init__(self):
        self._running = True
        self._display_surf = None
        self._image_surf = None
        self.player = Player() 
 
    def on_init(self):
        pygame.init()
        self._display_surf = pygame.display.set_mode((self.windowWidth,self.windowHeight), pygame.HWSURFACE)
 
        pygame.display.set_caption('Pygame pythonspot.com example')
        self._running = True
        self._image_surf = pygame.image.load("pygame.png").convert()
 
    def on_event(self, event):
        if event.type == QUIT:
            self._running = False
 
    def on_loop(self):
        pass
 
    def on_render(self):
        self._display_surf.fill((0,0,0))
        self._display_surf.blit(self._image_surf,(self.player.x,self.player.y))
        self.player.update()
        pygame.display.flip()
        sleep(0.03)
 
    def on_cleanup(self):
        pygame.quit()
 
    def on_execute(self):
        if self.on_init() == False:
            self._running = False
 
        while( self._running ):
            pygame.event.pump()
            keys = pygame.key.get_pressed() 
 
            if (keys[K_RIGHT]):
                self.player.moveRight()
 
            if (keys[K_LEFT]):
                self.player.moveLeft()
 
            if (keys[K_UP]):
                self.player.jump()
 
            if (keys[K_ESCAPE]):
                self._running = False
 
            self.on_loop()
            self.on_render()
        self.on_cleanup()
 
if __name__ == "__main__" :
    theApp = App()
    theApp.on_execute()

如果对象要跳跃,只需将它们添加到屏幕上,进行碰撞检测并在碰撞为真时重置跳跃变量。