Wrap Around the Screen
Part of the The Game Loop section of Coddy's Pygame journey. Lesson 25 of 35.
In many space games, a ship or a rock that leaves one side of the screen comes back on the other. This is wrapping. The rock here drifts up and to the right, and after a few seconds it is gone for good.
Test each edge after moving. The rock's radius is 20, so let it get fully out of sight before it jumps: past 480 + 20 on the right, it comes back at -20, out of sight past the left edge, and slides in.
if pos.x > 500:
pos.x = -20
if pos.x < -20:
pos.x = 500The same goes for y with the height: past 380 at the bottom it comes back at -20, and above -20 it comes back at 380.
Only the position jumps. The velocity stays, so the rock keeps drifting the same way after it wraps.
Challenge
EasyWrap the rock around the window, after pos += vel * dt.
- Above 500,
pos.xbecomes -20; below -20, it becomes 500. - Above 380,
pos.ybecomes -20; below -20, it becomes 380.
Press Play: the rock leaves one side and comes back on the other. Then Check.
Try it yourself
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Drifting Rock")
clock = pygame.time.Clock()
pos = pygame.Vector2(240, 180)
vel = pygame.Vector2(120, -70)
dt = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pos += vel * dt
screen.fill((20, 20, 34))
pygame.draw.circle(screen, (150, 150, 160), pos, 20)
pygame.display.flip()
dt = clock.tick(60) / 1000
pygame.quit()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in The Game Loop
Practice on your own: Pygame playground