我如何让我的角色开始使用pygame跳跃?

时间:2019-09-30 04:10:00

标签: python pygame

我正在程序中尝试跳跃代码,但字符没有跳跃。 (字符1s控件为'a''d',字符2s控件为'左箭头''右箭头'。我如何使字符1随w跳而字符2随上箭头跳。我不确定代码有什么问题,因为这是我第一次实现跳跃机制。

import pygame

pygame.init()

win = pygame.display.set_mode((700, 480))
pygame.display.set_caption("First project")
run = True
red = (255, 0, 0)
green = (0, 255, 0)


def drawbg():
    pygame.display.update()
    win.fill((255, 255, 255))


class person(object):
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = 5
        self.IsJump = False
        self.jumpCount = 10


man = person(100, 400, 50, 60)
man2 = person(500, 400, 50, 60)

while run:
    pygame.time.delay(25)


    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT] and man2.x > man2.vel:
        man2.x -= man2.vel

    if keys[pygame.K_RIGHT] and man2.x < 700 - man2.width - man2.vel:
        man2.x += man2.vel

    if keys[pygame.K_a] and man.x > man.vel:
        man.x -= man.vel

    if keys[pygame.K_d] and man.x < 700 - man.width - man.vel:
        man.x += man.vel

    if not man.IsJump and keys[pygame.K_SPACE]:
        man.IsJump = True
        man.JumpCount = 10

    if man.IsJump:
        if man.JumpCount >= -10:
            neg = 1
            if man.JumpCount < 0:
                neg = -1
            man.y -= (man.JumpCount ** 2) / 2 * neg
            man.JumpCount -= 1
        else:
            man.IsJump = False
            man.JumpCount = 10

    pygame.draw.rect(win, red, (man.x, man.y, man.width, man.height))
    pygame.draw.rect(win, green, (man2.x, man2.y, man2.width, man2.height))
    drawbg()

pygame.quit()

2 个答案:

答案 0 :(得分:1)

将处理跳转的代码移至类update的{​​{1}}方法中:

person

激活 k 上的播放器1(class person(object): def __init__(self, x, y, width, height): self.x = x self.y = y self.width = width self.height = height self.vel = 5 self.IsJump = False self.jumpCount = 10 def update(self): if self.IsJump: if self.JumpCount >= -10: neg = 1 if self.JumpCount >= 0 else -1 self.y -= (self.JumpCount ** 2) / 2 * neg self.JumpCount -= 1 else: self.IsJump = False self.JumpCount = 10 )的跳转,以及 UP 上的播放器2(man)的跳转。
事件处理后,为对象man2update调用man方法:

man2

答案 1 :(得分:0)

似乎您一开始并没有编写代码来响应键盘输入w(pygame.K_w)和向上(pygame.K_UP)。但是,在您上传的代码中,player1(man)已经可以使用空格键(K_SPACE)正确跳转。您可以复制该部分,而只需更改man2的一些变量。