Spin from the Original
Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 9 of 36.
A spike ball that spins all the time turns a little every frame. There is a tempting way to write it, and it breaks:
ball = pygame.transform.rotate(ball, 2) # wrongEach frame turns the last turned picture. Every rotation adds a see-through border, so the Surface grows about 3 percent a frame: twice the size after half a second, nearly 1,800 pixels wide after two. The pixels also smear a bit more with each turn. The game soon slows to a crawl.
Keep the original and the angle instead, and make the turned picture from the original every frame:
angle += 2
spun = pygame.transform.rotate(ball, angle)
screen.blit(spun, spun.get_rect(center=(320, 240)))Now spun is one rotation away from the file, whatever the angle: never bigger than 67 by 67 pixels and never blurrier than one turn. The same rule holds for every transform: work from the original, not from the last copy.
Challenge
Medium- Before the loop, make
angle = 0. - Each frame, add 2 to
angle. - Rotate the original
ballbyangleand draw the result with its centre at(320, 240). Never changeballitself.
Try it yourself
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Spinning Spikes")
clock = pygame.time.Clock()
ball = pygame.image.load("assets/images/spike_ball.png").convert_alpha()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((20, 22, 40))
screen.blit(ball, ball.get_rect(center=(320, 240)))
pygame.display.flip()
clock.tick(60)
pygame.quit()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Sprites and Images
3Classes for Game Objects
Your First ClassMethodsSelf Is the ObjectA List of ObjectsObjects with ImagesA SubclassPractice on your own: Pygame playground