Rotate Around the Centre
Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 6 of 39.
A ship that turns needs a turned picture. pygame.transform.rotate(image, angle) gives you a new Surface: the image turned by angle degrees counterclockwise. A negative angle turns it clockwise. The original image does not change.
A turned square does not fit in a square of the same size, so the new Surface is bigger: the ship turned 45 degrees is 90 by 90 pixels. Blit it at the old top left corner and its middle moves down and to the right; turning makes the ship wobble around the window.
Keep the middle where it was instead. Ask the turned image for a Rect centred on the same point:
rotated = pygame.transform.rotate(ship, angle)
rotated_rect = rotated.get_rect(center=(320, 240))
screen.blit(rotated, rotated_rect)Turn the original ship by the whole angle each frame. The ship's direction is the number in angle, and the picture is made from it.
Challenge
MediumTurn the ship in place with the arrows.
- Before the loop, make
angle = 0. - Holding Left adds 3 to
angleeach frame; holding Right takes 3 away. - Each frame, rotate
shipbyangleand draw the result with its centre at(320, 240).
Press Play and hold Left: the ship turns in place. Then Check.
Try it yourself
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Turn the Ship")
clock = pygame.time.Clock()
ship = pygame.image.load("assets/images/ship.png").convert_alpha()
ship_rect = ship.get_rect(center=(320, 240))
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()
All lessons in Sprites and Images
Practice on your own: Pygame playground