Move the Image
Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 3 of 36.
The ship sits at the bottom of the window. To fly it left and right, move its Rect with the arrow keys, the way you moved the square in section 2:
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
ship_rect.x -= 6
if keys[pygame.K_RIGHT]:
ship_rect.x += 6The blit line does not change: it draws at wherever the Rect is now.
A Rect can keep itself inside another Rect. screen.get_rect() is the window's Rect, (0, 0, 640, 480), and
ship_rect.clamp_ip(screen.get_rect())moves ship_rect back inside it when it pokes out. The _ip means in place: it changes ship_rect itself. ship_rect.clamp(...) without it leaves ship_rect alone and gives you a new Rect instead.
Challenge
Easy- In the loop, before drawing, holding Left moves
ship_rect6 pixels left and holding Right moves it 6 pixels right. - Then keep it in the window with
ship_rect.clamp_ip(screen.get_rect()).
Try it yourself
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()
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