Menu
CoddyTech

用 Rect 放置图像

本课属于 Coddy Pygame 学习旅程的“精灵与图像”单元。第 2 课,共 39 课。

手动计算左上角位置,意味着每放置一张图片都要做加法。每个 Surface 都可以根据自身尺寸创建一个 Rect:

ship_rect = ship.get_rect(center=(320, 400))

单独使用 get_rect() 得到的是 Rect(0, 0, 64, 64)。你可以用一个关键字指定位置:center、midbottom、topleft,或 Rect 上的其他任意点。这里,飞船的中心位于 (320, 400),pygame 会计算出左上角位置 (288, 368)。

将图片绘制到 Rect 上,它就会显示在 Rect 的左上角:

screen.blit(ship, ship_rect)

现在,Rect 就是飞船的位置。更改 ship_rect.x 或 ship_rect.centery,下一帧就会在新位置绘制飞船。游戏中的每张图片都是这样移动的:保留一个 Rect,更改这个 Rect,然后绘制到 Rect 上。你还会用这个 Rect 检测碰撞,就像第 2 单元中那样。

challenge icon

挑战

简单

用 Rect 放置飞船。

  1. 加载 ship 后,创建 ship_rect = ship.get_rect(center=(320, 400))。
  2. 在 ship_rect 处绘制 ship,而不是使用固定坐标。

按“开始”:飞船会位于靠近底部的位置。然后按“检查”。

亲手试试

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()

精灵与图像中的所有课

自己练习: Pygame 在线编辑器