Rectで配置する
CoddyのPygameジャーニー「スプライトと画像」セクションの一部。レッスン 2/39。
左上の角を手作業で求めるには、配置する画像ごとに計算が必要です。各 Surface は、自身のサイズの Rect を取得できます。
ship_rect = ship.get_rect(center=(320, 400))get_rect() だけなら Rect(0, 0, 64, 64) です。キーワードを指定すると位置を決められます。center、midbottom、topleft、または Rect が持つほかの任意の点を指定します。ここでは船の中央が (320, 400) に配置され、pygame が角の座標 (288, 368) を計算します。
Rect の位置に画像を blit すると、Rect の左上の角に配置されます。
screen.blit(ship, ship_rect)これで Rect が船の位置を表します。ship_rect.x または ship_rect.centery を変更すると、次のフレームでは船がその位置に描画されます。ゲーム内のすべての画像はこのように動かします。Rect を保持し、Rect を変更して、Rect の位置に blit します。セクション 2 のように、衝突判定にもこの Rect を使います。
チャレンジ
簡単Rectを使って船を配置します。
shipを読み込んだ後、ship_rect = ship.get_rect(center=(320, 400))を作成します。- 固定位置ではなく、
ship_rectにshipを描画します。
「プレイ」を押すと、船が画面下部付近に表示されます。その後、「確認」を押します。
自分で試してみよう
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Space Images")
clock = pygame.time.Clock()
ship = pygame.image.load("assets/images/ship.png").convert_alpha()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((20, 22, 40))
screen.blit(ship, (288, 208))
pygame.display.flip()
clock.tick(60)
pygame.quit()
スプライトと画像のすべてのレッスン
自分で練習してみよう: Pygameプレイグラウンド