当我在 pygame 中按下特定键时,为什么我的精灵不移动

Why isn't my sprite moving when i press a specific key in pygame

我正在构建一个简单的火箭游戏,它需要移动一些精灵。在下面的代码中,每次我按下 K_DOWN 键时,cloud1 应该向底部移动 -30 像素。 3天来我一直在试图找出代码有什么问题,但一点进展都没有。将不胜感激。

import pygame
pygame.init()

DISPLAY_HEIGHT = 700
DISPLAY_WIDTH = 900

screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
pygame.display.set_caption('Rocket Game')

clock = pygame.time.Clock()
FPS = 60


#colors
WHITE = (255,255,255)
BLACK = (0,0,0)
SKY_BLUE = (102,178,255)

cloud1 = pygame.image.load('cloud.png')
cloud1_X, cloud1_Y = 100, 50
cloud1_Y_change = 30


def cloud1_display(x, y):
    screen.blit(cloud1, (x, y))

running = True
while running:
    screen.fill(SKY_BLUE)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                cloud1_Y += cloud1_Y_change

    cloud1_display(cloud1_X, cloud1_X)
    clock.tick(FPS)
    pygame.display.update()


    
    

对于你的主游戏循环,第二次尝试使用 event.key 而不是 event.type。像这样:

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

    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_UP:
            cloud1_Y += cloud1_Y_change

我注意到的另一个问题是您没有在 pygame 中将图像转换为矩形对象,然后使用 .blit 在屏幕上显示它。 .blit 函数需要一个 rect 对象参数,所以这就是你遇到问题的原因。

cloud1 = pygame.image.load('asteroid_pic.bmp')
rect =  cloud1.get_rect()
screen.blit(cloud1, self.rect)

我还建议为您的精灵创建单独的 classes,这样更容易跟踪它们,如果您想创建相同的副本但仍保留单个 class sprite 您可以通过从 pygame.sprite.

导入函数 Group 来实现

有两个问题。首先是您的代码没有检查 event.key 中的 pygame.K_UP。但是您的代码也在 (x, x) 处绘制了云,而不是 (x, y)

更正后的代码:

while running:
    screen.fill(SKY_BLUE)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:       # <<-- HERE
                cloud1_Y += cloud1_Y_change

    cloud1_display(cloud1_X, cloud1_Y)         # <<-- AND HERE
    clock.tick(FPS)
    pygame.display.update()