我不知道为什么我的球员没有跳。我已经定义了jump
和update
函数,如下所示:
def jump(self):
if self.is_jumping == False:
self.is_jumping = True
def update(self):
if self.is_jumping:
self.y -= self.force
这是初始化
class Myman:
def __init__(self, x, y, side):
self.x = x
self.y = y
self.side = side
self.speed = 2
self.is_jumping = False
我已经在主循环中实现了这一点,如下所示:
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
mm.jump()
d.fill((98, 98, 98))
mm.draw()
mm.g()
mm.update()
if mm.y + mm.side > 550:
mm.y = 550 - mm.side
mm.falling = False
但是,当我尝试跳时,它不起作用。到目前为止,我所见过的所有例子都做过同样的事情,但是我的却行不通,我也不知道为什么。感谢您的帮助。
这是想要检查参考的任何人的代码。
import pygame, os
os.environ["SDL_VIDEO_CENTERED"] = "1"
pygame.init()
win = pygame.display
d = win.set_mode((1200, 600))
win.set_caption("Jump")
gravity = 0.1
class Myman:
def __init__(self, x, y, side):
self.x = x
self.y = y
self.side = side
self.speed = 2
self.is_jumping = False
self.force = 2
def draw(self):
pygame.draw.rect(d, (0 ,255, 0), (self.x, self.y, self.side, self.side))
def g(self):
global gravity
self.y += gravity
gravity += 0.01
def move_left(self):
self.x -= self.speed
def move_right(self):
self.x += self.speed
def jump(self):
if self.is_jumping == False:
self.is_jumping = True
def update(self):
if self.is_jumping:
self.y -= self.force
mm = Myman(600, 400, 20)
def platform():
pygame.draw.rect(d, (0 ,0, 0), (0, 550, 1200, 50))
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
mm.jump()
d.fill((98, 98, 98))
mm.draw()
mm.g()
mm.update()
platform()
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT]:
mm.move_right()
if keys[pygame.K_LEFT]:
mm.move_left()
if mm.y + mm.side >= 550:
mm.y = 550 - mm.side
mm.falling = False
win.flip()
答案 0 :(得分:2)
问题在于您的重力在不断增加:
def g(self):
global gravity
self.y += gravity
gravity += 0.01 # <-- HERE
仅一秒钟后,重力为每帧60
个像素。这比逆转比跳跃引起的任何微小速度变化要好得多。
因此,除非您想建立一个实时的“物理”重力模型(这会很好),否则也许只需在跳跃的毫秒时间内更改玩家的重力即可。在跳跃的前半段给它负的重力,然后在跳跃的最高点,重力恢复为正常。根据跳转时间很容易做到这一点。
类似的东西:
class Myman:
JUMP_TIME = 1500 # milliseconds to jump apogee
def __init__(self, x, y, side):
self.x = x
self.y = y
self.jump_at = 0 # time of jump start
# ... rest of code omitted
def isJumping( self ):
jumping = False
time_now = pygame.time.get_ticks()
if ( time_now - self.jump_at < 2 * Myman.JUMP_TIME ): # up and down time
jumping = True
return jumping
def jump( self ):
if ( not self.isJumping() ): # is the player ready to jump again
self.jump_at = pygame.time.get_ticks() # time now
def update( self ):
if ( self.isJumping() ):
time_now = pygame.time.get_ticks()
# is the player going up, or coming down?
if ( time_now - self.jump_at < Myman.JUMP_TIME ):
self.gravity = -0.1 # still jumping up
else:
self.gravity = 0.1 # now going down
# ... rest of code omitted
样式注:我有目的地在所有if
表达式前后加上方括号,因为我真的相信它可以使代码更具可读性。这与PEP8中的建议相反。
答案 1 :(得分:0)
希望这可以解决您的问题,但代码缩进不正确。
从d.fill((98, 98, 98))
到win.flip()
,您的代码可能还需要另外4个空格/ 1个制表符才能匹配for循环