Vector2
Part of the The Game Loop section of Coddy's Pygame journey. Lesson 20 of 32.
A position is two numbers, and so is a velocity: the speed in x and the speed in y. pygame.Vector2 keeps two numbers together and does arithmetic on both at once:
pos = pygame.Vector2(240, 180)
vel = pygame.Vector2(150, 90)
pos += vel * dtvel * dt multiplies both parts and pos += ... adds both parts, so one line moves the ball 150 pixels a second to the right and 90 down. pos.x and pos.y read or change one part, and pygame.draw.circle takes a Vector2 as its centre.
To bounce off a wall, turn one part of the velocity around. Past a side, vel.x = -vel.x sends the ball back and leaves its up and down speed alone:
if pos.x < 16 or pos.x > 464:
vel.x = -vel.xThe ball's radius is 16, so at 16 and 464 its edge touches the window's sides.
Challenge
Medium- Replace
x, ywithpos = pygame.Vector2(240, 180)andvx, vywithvel = pygame.Vector2(150, 90). - Move the ball with
pos += vel * dtand draw it atpos. - Turn
vel.xaround whenpos.xis below 16 or above 464, andvel.ywhenpos.yis below 16 or above 344.
Try it yourself
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()
All lessons in The Game Loop
Practice on your own: Pygame playground