이미지 이동하기
Coddy Pygame 여정의 스프라이트와 이미지 섹션에 포함된 레슨. 36개 중 3번째.
우주선은 창의 아래쪽에 있습니다. 좌우로 움직이려면 2절에서 사각형을 움직였던 것처럼 화살표 키로 우주선의 Rect를 움직이세요:
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
ship_rect.x -= 6
if keys[pygame.K_RIGHT]:
ship_rect.x += 6blit 줄은 바뀌지 않습니다. Rect가 현재 있는 위치에 그립니다.
Rect는 다른 Rect 안에 머물 수 있습니다. screen.get_rect()는 창의 Rect, (0, 0, 640, 480)이며,
ship_rect.clamp_ip(screen.get_rect())우주선이 바깥으로 삐져나오면 ship_rect를 다시 안쪽으로 옮깁니다. _ip는 제자리에서(in place)라는 뜻입니다. ship_rect 자체를 바꿉니다. _ip 없이 ship_rect.clamp(...)를 사용하면 ship_rect는 그대로 두고 대신 새 Rect를 반환합니다.
챌린지
쉬움- 루프에서 그리기 전에 왼쪽 키를 누르고 있으면
ship_rect가 왼쪽으로 6픽셀 이동하고, 오른쪽 키를 누르고 있으면 오른쪽으로 6픽셀 이동합니다. - 그런 다음
ship_rect.clamp_ip(screen.get_rect())를 사용해 창 안에 유지합니다.
직접 해보기
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()
ship_rect = ship.get_rect(center=(320, 400))
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, ship_rect)
pygame.display.flip()
clock.tick(60)
pygame.quit()
스프라이트와 이미지의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드