Menu
CoddyTech

Face the Way You Fly

Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 7 of 36.

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_left

Draw 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 icon

Challenge

Medium
  1. Before the loop, make ship_left: ship_right flipped left to right.
  2. Make image = ship_right before the loop.
  3. Holding Left sets image = ship_left; holding Right sets image = ship_right. The movement stays as it is.
  4. Draw image at ship_rect.

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()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Sprites and Images

Practice on your own: Pygame playground