Face the Way You Fly
Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 7 of 39.
The ship points up in its file. Turned with rotate(ship, -90) it points right, which suits a ship flying sideways. When it flies left, it should point left.
pygame.transform.flip(image, flip_x, flip_y) gives you a mirrored copy. True, False mirrors it left to right; False, True mirrors it top to bottom.
ship_right = pygame.transform.rotate(ship, -90)
ship_left = pygame.transform.flip(ship_right, True, False)Both pictures are made once, before the loop. The game then remembers which one to show in a variable, and the keys change it:
if keys[pygame.K_LEFT]:
ship_rect.x -= 5
image = ship_leftDraw image each frame. When no key is held, image keeps its last value, so the ship goes on facing the way it last flew.
Challenge
MediumMake the ship face the way it flies.
- Before the loop, make
ship_left,ship_rightflipped left to right, andimage = ship_right. - Holding Left sets
image = ship_left; holding Right setsimage = ship_right. - Draw
imageatship_rect.
Press Play and fly left: the ship faces left. Then Check.
Try it yourself
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Face the Way You Fly")
clock = pygame.time.Clock()
ship = pygame.image.load("assets/images/ship.png").convert_alpha()
ship_right = pygame.transform.rotate(ship, -90)
ship_rect = ship_right.get_rect(center=(320, 240))
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]:
ship_rect.x -= 5
if keys[pygame.K_RIGHT]:
ship_rect.x += 5
ship_rect.clamp_ip(screen.get_rect())
screen.fill((20, 22, 40))
screen.blit(ship_right, ship_rect)
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Sprites and Images
Practice on your own: Pygame playground