Vector2
本课属于 Coddy Pygame 学习旅程的“游戏循环”单元。第 23 课,共 35 课。
位置由两个数字组成,速度也是如此:x 方向的速度和 y 方向的速度。pygame.Vector2 将两个数字放在一起,并同时对它们进行算术运算:
pos = pygame.Vector2(240, 180)
vel = pygame.Vector2(150, 90)
pos += vel * dtvel * dt 会将两个分量都相乘,pos += ... 会将两个分量都相加,因此只用一行代码,就能让球以每秒向右 150 像素、向下 90 像素的速度移动。pos.x 和 pos.y 可以读取或更改其中一个分量,而 pygame.draw.circle 接受 Vector2 作为圆心。
要让球撞墙反弹,可以反转速度的一个分量。球越过侧边后,vel.x = -vel.x 会让球向回运动,同时保持上下方向的速度不变:
if pos.x < 16 or pos.x > 464:
vel.x = -vel.x球的半径是 16,所以当位置在 16 和 464 时,球的边缘正好碰到窗口的两侧。
挑战
中等用两个 Vector2 让球在窗口中来回弹跳。
- 将
x, y替换为pos = pygame.Vector2(240, 180),将vx, vy替换为vel = pygame.Vector2(150, 90)。 - 使用
pos += vel * dt移动球,并在pos处绘制它。 - 当
pos.x小于 16 或大于 464 时,让vel.x反向;当pos.y小于 16 或大于 344 时,让vel.y反向。
按“运行”:球会在窗口中来回弹跳。然后按“检查”。
亲手试试
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Bounce")
clock = pygame.time.Clock()
x, y = 240, 180
vx, vy = 150, 90
dt = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
x += vx * dt
y += vy * dt
screen.fill((30, 30, 46))
pygame.draw.circle(screen, (80, 160, 255), (x, y), 16)
pygame.display.flip()
dt = clock.tick(60) / 1000
pygame.quit()
游戏循环中的所有课
自己练习: Pygame 在线编辑器