Moving A Sprite To The Other Side When A Sprite Moves Off Screen Pygame
If I have a sprite (See below) that I can move around, the screen with the arrow keys. (Up and Down moves forwards and backwards, left and right turn.) I was wondering if it would
Solution 1:
I'm not too familiar with pygame but I think this game (md5: 92f9f508cbe2d015b18376fb083e0064 file: spacegame.zip) has the feature you're looking for. Thanks to the author, DR0ID_ , for making it publicly available on his/her website
To implement the "wrap around" feature in your car game I used this function from "game.py":
def draw(self, surface):
wrap = 0for s inself.sprites():
r = s.rect
if r.left<0:
r.move_ip(800, 0)
wrap = 1
elif r.right > 800:
r.move_ip(-800, 0)
wrap = 1if r.top < 0:
r.move_ip(0, 600)
wrap = 1
elif r.bottom > 600:
r.move_ip(0, -600)
wrap = 1ifwrap:
surface_blit(s.image, r)
wrap = 0
After a few adjustments I ended up with this working example:
import sys, pygame, math
from pygame.locals import *
pygame.init()
# Added HEIGHT and WIDTH as fixed variables
WIDTH = 800
HEIGHT = 600
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
car = pygame.transform.scale(pygame.image.load('Car.png').convert_alpha(), (64, 64))
pygame.display.set_caption('Car Game')
pygame.display.set_icon(car)
FPS = pygame.time.Clock()
carX = 400
carY = 100
angle = 90
speed = 0whileTrue:
if angle == 360: angle = 0if angle == -1: angle = 359
SCREEN.fill((0,0,0))
foreventin pygame.event.get():
ifevent.type == QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
if keys[K_a] or keys[K_LEFT]:
angle += speed
elif keys[K_d] or keys[K_RIGHT]:
angle -= speed
if keys[K_w] or keys[K_UP]:
speed += 1
elif keys[K_s] or keys[K_DOWN]:
speed -= 0.5
carX += speed*math.cos(math.radians(angle))
carY -= speed*math.sin(math.radians(angle))
speed *= 0.95
rotcar = pygame.transform.rotate(car, angle)
position = rotcar.get_rect(center = (carX,carY))
# Basically a copy/paste of the "draw"-functionfrom the spacegame.zip
wrap_around = Falseif position[0] < 0 :
# off screen left
position.move_ip(WIDTH, 0)
wrap_around = Trueif position[0] + rotcar.get_width() > WIDTH:
# off screen right
position.move_ip(-WIDTH, 0)
wrap_around = Trueif position[1] < 0:
# off screen top
position.move_ip(0, HEIGHT)
wrap_around = Trueif position[1] + rotcar.get_height() > HEIGHT:
# off screen bottom
position.move_ip(0, -HEIGHT)
wrap_around = Trueif wrap_around:
SCREEN.blit(rotcar, position)
position[0] %= WIDTH
position[1] %= HEIGHT
carX %= WIDTH
carY %= HEIGHT
SCREEN.blit(rotcar, position)
pygame.display.update()
FPS.tick(24)
Solution 2:
Instead of using "elif"-statements, you can just set the coordinates "modulo" (%) screen-width / screen height, for x and y coordinates individually.
Post a Comment for "Moving A Sprite To The Other Side When A Sprite Moves Off Screen Pygame"