重力で落下する
CoddyのPygameジャーニー「ゲームの世界」セクションの一部。レッスン 10/35。
ウィンドウ内のヒーローは、リフトのように毎フレーム一定の4ピクセルずつ落下します。実際の物体は落下するにつれて速度が上がります。プレイヤーの垂直方向の速度を変数に保持し、毎フレーム増やしていきましょう。
vel_y += GRAVITY
player.y += vel_y
if player.bottom > FLOOR:
player.bottom = FLOOR
vel_y = 0vel_yは1フレームあたりのピクセル単位の速度です。正の値は下方向を表します。GRAVITY = 1は毎フレーム速度に1を加えるので、プレイヤーは1ピクセル、次に2ピクセル、次に3ピクセルと落下していきます。
ここでの床は、草の上端にあるFLOOR = 324の位置の線です。プレイヤーがその線を通り過ぎたら、下端を線に合わせて落下を止めます。次の章では、この線を実際の足場に置き換えます。
プレイヤーは画像のRectです。player_img.get_rect(topleft=(264, 40))はその位置にある48×48のRectで、screen.blit(player_img, player)はそこに画像を描画します。
チャレンジ
簡単- 先頭に
GRAVITY = 1を追加し、ゲームループの前にvel_y = 0を追加します。 - 各フレームで、
GRAVITYをvel_yに加え、次にvel_yをplayer.yに加えます。player.y += 4の代わりに行います。 player.bottomがFLOORを超えたら、player.bottom = FLOORおよびvel_y = 0を設定します。
自分で試してみよう
import pygame
TILE = 36
FLOOR = 324
pygame.init()
screen = pygame.display.set_mode((576, 360))
pygame.display.set_caption("Gravity")
clock = pygame.time.Clock()
background = pygame.image.load("assets/backgrounds/clouds.png").convert_alpha()
grass_img = pygame.image.load("assets/images/grass.png").convert_alpha()
player_img = pygame.image.load("assets/images/player.png").convert_alpha()
player = player_img.get_rect(topleft=(264, 40))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player.x -= 4
if keys[pygame.K_RIGHT]:
player.x += 4
player.y += 4
if player.bottom > FLOOR:
player.bottom = FLOOR
for y in range(0, 360, 72):
for x in range(0, 576, 72):
screen.blit(background, (x, y))
for x in range(0, 576, TILE):
screen.blit(grass_img, (x, FLOOR))
screen.blit(player_img, player)
pygame.display.flip()
clock.tick(60)
pygame.quit()
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ゲームの世界のすべてのレッスン
自分で練習してみよう: Pygameプレイグラウンド