在本文中,您将学习如何在 Pygame 中实现跳和跑逻辑。 为此,我们将实现玩家逻辑。
移动
左右移动与上一教程类似,只是意味着更改玩家的(x, y)位置。 对于跳跃,我们使用经典力学中的公式:
F = 1/2 * m * v^2
其中F是向上/向下的力,m是物体的质量,v是速度。 速度会随着时间的推移而下降,因为在此模拟中,当玩家跳跃时速度不会增加更多。 如果玩家到达地面,则跳跃结束。 在 Python 中,我们设置了一个变量isjump来指示玩家是否在跳跃。 如果是玩家,则其位置将根据以上公式进行更新。
完整代码:
from pygame.locals import *import pygameimport mathfrom time import sleepclass Player:x = 10y = 500speed = 10# Stores if player is jumping or not.isjump = 0# Force (v) up and mass m.v = 8m = 2def moveRight(self):self.x = self.x + self.speeddef moveLeft(self):self.x = self.x - self.speeddef jump(self):self.isjump = 1def 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 positionself.y = self.y - F# Change velocityself.v = self.v - 1# If ground is reached, reset variables.if self.y >= 500:self.y = 500self.isjump = 0self.v = 8class App:windowWidth = 800windowHeight = 600player = 0def __init__(self):self._running = Trueself._display_surf = Noneself._image_surf = Noneself.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 = Trueself._image_surf = pygame.image.load("pygame.png").convert()def on_event(self, event):if event.type == QUIT:self._running = Falsedef on_loop(self):passdef 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 = Falsewhile( 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 = Falseself.on_loop()self.on_render()self.on_cleanup()if __name__ == "__main__" :theApp = App()theApp.on_execute()
如果要跳跃对象,只需将它们添加到屏幕上,进行碰撞检测,如果碰撞为true,则重置跳跃变量。
