Place It with a Rect
Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 2 of 39.
Working out a top left corner by hand means sums for every image you place. Every Surface can give you a Rect of its own size:
ship_rect = ship.get_rect(center=(320, 400))get_rect() alone is Rect(0, 0, 64, 64). A keyword places it: center, midbottom, topleft, or any other point a Rect has. Here the ship's middle goes at (320, 400) and pygame works out the corner, (288, 368).
Blit the image at the Rect and it lands on the Rect's top left corner:
screen.blit(ship, ship_rect)Now the Rect is the ship's position. Change ship_rect.x or ship_rect.centery and the next frame draws the ship there. This is how every image in a game moves: keep a Rect, change the Rect, blit at the Rect. It is also the Rect you test collisions with, as in section 2.
Challenge
EasyPlace the ship with a Rect.
- After loading
ship, makeship_rect = ship.get_rect(center=(320, 400)). - Blit
shipatship_rectinstead of a fixed point.
Press Play: the ship sits near the bottom. Then Check.
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()
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, (288, 208))
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Sprites and Images
Practice on your own: Pygame playground