How to make the background continuously scrolling

2019-05-23 00:55发布

问题:

I am planning to create a space shooting game and i want my background with stars continuously moving down wards. You can see my codes below. Image http://tinypic.com/r/9a8tj4/5

import pygame
import sys
import pygame.sprite as sprite

theClock = pygame.time.Clock()

background = pygame.image.load('background.gif')

background_size = background.get_size()
background_rect = background.get_rect()
screen = pygame.display.set_mode(background_size)
x = 0
y = 0
w,h = background_size
running = True

while running:
    screen.blit(background,background_rect)
    pygame.display.update()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    if(y > h):
        y = 0
    else:
        y += 5
    screen.blit(background,(x,y))
    pygame.display.flip()
    pygame.display.update()
    theClock.tick(10)

回答1:

Here's what i would do:

Blit the surface with the background image twice one at (0, 0) and another at (0,- img.height) then move them down and when either of them are at pos(0, img.heigth) place it at pos (0,- img.height) again.

import pygame
import sys
import pygame.sprite as sprite

theClock = pygame.time.Clock()

background = pygame.image.load('background.gif')

background_size = background.get_size()
background_rect = background.get_rect()
screen = pygame.display.set_mode(background_size)
w,h = background_size
x = 0
y = 0

x1 = 0
y1 = -h

running = True

while running:
    screen.blit(background,background_rect)
    pygame.display.update()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    y1 += 5
    y += 5
    screen.blit(background,(x,y))
    screen.blit(background,(x1,y1))
    if y > h:
        y = -h
    if y1 > h:
        y1 = -h
    pygame.display.flip()
    pygame.display.update()
    theClock.tick(10)


标签: python pygame