python - 如何修复我的 'Jump' ?

标签 python pygame

我是这个网站和 pygame 的新手,所以请耐心等待。我正在尝试 pygame 并制作了一个简单的平台游戏。然而,每当我“跳跃”时, block 就会逐帧跳跃,所以我必须按住空格键。任何帮助将不胜感激! 这是我的代码:

import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
x = 0
y = 490
width = 10
height = 10
vel = 5
pygame.key.set_repeat(1)
isjump = False
jumpcount = 10
while True:
    pygame.time.delay(30)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            break
        keys = pygame.key.get_pressed()
        if keys[pygame.K_a] and x>vel-5:
            x -= vel
        if keys[pygame.K_d] and x < 500 - width:
            x += vel
        if not(isjump):
            if keys[pygame.K_SPACE]:
                isjump = True
        else:
            if jumpcount >= -10:
                neg = 1
                if jumpcount < 0:
                    neg = -1
                y -= (jumpcount ** 2) /2 * neg
                jumpcount -= 1
            else:
                isjump = False
                jumpcount = 10
        win.fill((0, 0, 0))
        pygame.draw.rect(win, (255, 255, 255), (x, y, width, height))
        pygame.display.update()
pygame.quit()

最佳答案

您将键盘事件处理与跳转逻辑混合在一起。我做了两件事,更改空格键检测以触发 isjump 并处理跳转逻辑,无论是否按下按键:

import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
x = 0
y = 490
width = 10
height = 10
vel = 5
pygame.key.set_repeat(1)
isjump = False
jumpcount = 10
while True:
    pygame.time.delay(30)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            break
        keys = pygame.key.get_pressed()
        if keys[pygame.K_a] and x>vel-5:
            x -= vel
        if keys[pygame.K_d] and x < 500 - width:
            x += vel
        # if we're not already jumping, check if space is pressed to start a jump
        if not isjump and keys[pygame.K_SPACE]:
            isjump = True
            jumpcount = 10
    # if we're supposed to jump, handle the jump logic
    if isjump:
        if jumpcount >= -10:
            neg = 1
            if jumpcount < 0:
                neg = -1
            y -= (jumpcount ** 2) /2 * neg
            jumpcount -= 1
        else:
            isjump = False
            jumpcount = 10
    win.fill((0, 0, 0))
    pygame.draw.rect(win, (255, 255, 255), (x, y, width, height))
    pygame.display.update()
pygame.quit()

关于python - 如何修复我的 'Jump' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51962516/

相关文章:

python - 在 Celery 任务中使用 Redis 连接和保存数据

python - cv2 videowriter,写得很好,但在应用程序关闭时抛出错误

python - 有什么办法可以非暴力地停止 celery worker 的特定任务吗?

c++ - C++ SDL 和 (Python PyGame) 是否被业余爱好者以外的人使用?

python - 无缝播放音效pygame

python - 随着时间的推移改变变量

python - @staticmethod 和@classmethod 的区别

python - Django - 以 10 为基数的 int() 的无效文字 python django

python - 绑定(bind)多个 PyGame 窗口的可能性

python - py2exe 没有正确编译 VideoCapture