簡體   English   中英

Pygame rect 不會更新

[英]Pygame rect will not update

我正在 pygame 中構建一個游戲,其中有一個紅色目標在屏幕右側上下移動,屏幕左側有一艘船上下移動發射子彈(這只是一個藍色矩形) ) 目標。

我的船和我的目標從屏幕兩側的中心開始,並且正在正確移動。 我遇到的問題是,當我“發射”一顆子彈時,子彈會被拉到飛船的原始位置,而不是飛船移動到屏幕上的位置。

我將子彈的矩形設置為 while 循環之外的船舶圖像的矩形,但我認為它會隨着我的船在屏幕上上下移動而更新。

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()

我將子彈的矩形設置為 while 循環之外的船舶圖像的矩形,但我認為它會隨着我的船在屏幕上上下移動而更新。

不是這個。 你只是設置矩形的位置,沒有自動更新。 您必須編寫代碼以使它們保持同步。
但更簡單的是,在您的情況下,您可以在射擊時創建子彈矩形。 像這樣在循環中移動子彈創建:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM