플랫폼에 착지하기
Coddy Pygame 여정의 게임 월드 섹션에 포함된 레슨. 35개 중 16번째.
이제 벽이 플레이어를 받쳐 주도록 하세요. 옆 방향 이동 문제를 해결한 다음, y축 방향으로 이동하고 같은 방식으로 그 이동 문제를 해결하세요. 플레이어가 떨어지는 동안 벽과 겹치면 발이 벽의 위쪽에 닿도록 하세요.
vel_y = min(vel_y + GRAVITY, MAX_FALL)
player.y += vel_y
on_ground = False
for wall in walls:
if player.colliderect(wall):
if vel_y > 0:
player.bottom = wall.top
vel_y = 0
on_ground = Trueon_ground은 매 프레임 False로 시작하며, 착지할 때만 True가 됩니다. 난간에서 걸어 나가면 다음 프레임에는 플레이어 아래에 아무것도 없으므로 떨어지고 공중에서는 점프할 수 없습니다.
이 코드는 FLOOR 줄을 대체합니다. 맵의 맨 아래 행도 다른 벽과 마찬가지로 땅입니다. 중력이 매 프레임 플레이어를 땅속으로 1픽셀 끌어당기고, 착지 판정이 플레이어를 다시 올려 주므로 플레이어는 제자리에 서 있습니다.
챌린지
중급FLOOR줄 검사를 제거하세요.player.y += vel_y뒤에on_ground = False로 설정한 다음walls를 반복해서 확인하세요.vel_y > 0인 동안 플레이어가 충돌하는 각 벽에 대해 다음을 수행하세요.player.bottom = wall.top,vel_y = 0,on_ground = True.
직접 해보기
import pygame
TILE = 36
SPEED = 4
GRAVITY = 1
JUMP = -15
MAX_FALL = 12
FLOOR = 324
LEVEL = [
"................",
"................",
"................",
"....P.....###...",
"................",
"................",
"...####.........",
"............#...",
"#.......#...#..#",
"################",
]
pygame.init()
screen = pygame.display.set_mode((576, 360))
pygame.display.set_caption("Landing")
clock = pygame.time.Clock()
background = pygame.image.load("assets/backgrounds/clouds.png").convert_alpha()
block_img = pygame.image.load("assets/images/block.png").convert_alpha()
player_img = pygame.image.load("assets/images/player.png").convert_alpha()
walls = []
for row, line in enumerate(LEVEL):
for col, char in enumerate(line):
if char == "#":
walls.append(pygame.Rect(col * TILE, row * TILE, TILE, TILE))
elif char == "P":
start = (col * TILE + TILE // 2, row * TILE + TILE)
player = player_img.get_rect(midbottom=start)
vel_y = 0
on_ground = False
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN and event.key in (pygame.K_SPACE, pygame.K_UP):
if on_ground:
vel_y = JUMP
elif event.type == pygame.KEYUP and event.key in (pygame.K_SPACE, pygame.K_UP):
if vel_y < -4:
vel_y = -4
keys = pygame.key.get_pressed()
dx = 0
if keys[pygame.K_LEFT]:
dx -= SPEED
if keys[pygame.K_RIGHT]:
dx += SPEED
player.x += dx
for wall in walls:
if player.colliderect(wall):
if dx > 0:
player.right = wall.left
elif dx < 0:
player.left = wall.right
vel_y = min(vel_y + GRAVITY, MAX_FALL)
player.y += vel_y
on_ground = False
if player.bottom > FLOOR:
player.bottom = FLOOR
vel_y = 0
on_ground = True
for y in range(0, 360, 72):
for x in range(0, 576, 72):
screen.blit(background, (x, y))
for wall in walls:
screen.blit(block_img, wall)
screen.blit(player_img, player)
pygame.display.flip()
clock.tick(60)
pygame.quit()
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
게임 월드의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드