pygame rect不会更新

时间:2019-03-29 10:39:56

标签: python pygame pygame-surface

我正在pygame中构建一个游戏,其中一个红色目标在屏幕右侧上下移动,而一艘船在屏幕左侧上下移动,从而发射子弹(这只是目标上的一个蓝色矩形)。

我的船和我的目标从屏幕两边的中心开始,并且正在正确移动。我遇到的问题是,当我“发射”子弹时,子弹是从船的原始位置绘制的,而不是船在屏幕上移动的位置。

我在while循环之外将子弹的rect设置为船图像的rect,但是我认为当我的船在屏幕上上下移动时,它将更新。

import pygame
import pygame.sprite
import sys

screen_width = 1200
screen_height = 800
screen = pygame.display.set_mode((screen_width, screen_height))
screen_rect = screen.get_rect()

image = pygame.image.load('ship.bmp')
image_rect = image.get_rect()
image_rect.midleft = screen_rect.midleft

target_rect = pygame.Rect(400, 0, 100, 100)
target_color = (255, 0, 0)
target_rect.midright = screen_rect.midright
target_direction = 1

bullet_rect = pygame.Rect(0, 0, 15, 3)
bullet_rect.midright = image_rect.midright
bullet_color = (0, 0, 255)
fire_bullet = False


while True:

    screen.fill((0, 255, 0))

    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_q:
                sys.exit()

            # Move the ship up and down 
            elif event.key == pygame.K_UP:
                image_rect.y -= 45
            elif event.key == pygame.K_DOWN:
                image_rect.y += 45                
            # Active bullet fired 
            elif event.key == pygame.K_SPACE:
                fire_bullet = True

        elif event.type == pygame.QUIT:
                sys.exit()

    # Move the bullet across the screen if fired
    if fire_bullet:
        screen.fill(bullet_color, bullet_rect)
        bullet_rect.x += 1

    # Move the Target up and down
    target_rect.y += target_direction
    if target_rect.bottom >= screen_height:
        target_direction *= -1
    elif target_rect.top <= 0:
        target_direction *= -1


    screen.fill(target_color, target_rect)
    screen.blit(image, image_rect)
    pygame.display.flip()

1 个答案:

答案 0 :(得分:1)

  

我在while循环之外将子弹的rect设置为船图像的rect,但是我认为随着我的船在屏幕上上下移动,它会得到更新。

不是。您只需设置矩形的位置,就不会自动更新。您必须编写代码以使其保持同步。
但是更简单的是,在您的情况下,您可以在射击时创建子弹头。像这样在循环中移动项目符号创建:

elif event.key == pygame.K_SPACE:
    bullet_rect = pygame.Rect(0, 0, 15, 3)
    bullet_rect.midright = image_rect.midright
    bullet_color = (0, 0, 255)
    fire_bullet = True
相关问题