Rectで配置する
CoddyのPygameジャーニー「スプライトと画像」セクションの一部。レッスン 2/36。
左上隅を手計算で求めるには、配置する画像ごとに計算が必要です。どの 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 を使います。
チャレンジ
簡単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プレイグラウンド