Pygame:两层滚动背景,您能帮我吗?

时间:2019-04-01 11:52:44

标签: python scroll pygame

我想创建一个两层的滚动背景,但是每次我运行下面的程序时,都会出错,而且我也不知道为什么:/ 你能帮我吗?

我尝试了以下代码:

'bg scrolling try'

import pygame as pg
from pygame.locals import *
pg.init()

screen = pg.display.set_mode((1920, 1080), pg.NOFRAME)
a = True
land_0 = pg.image.load('sprites/land_0.png').convert_alpha()
land_1 = pg.image.load('sprites/land_1.png').convert_alpha()
bg = pg.image.load('sprites/bg.png').convert_alpha()

pos_l0_0 = 2
pos_l0_1 = 1920
pos_l1_0 = -1000
pos_l1_1 = 920
hight_land = 500
hight_land_1 = 400
s_speed = 2
while a:
     screen.blit(bg,(0, 0))
     pos_l1_0 = pos_l1_0 - s_speed
     pos_l1_1 = pos_l1_1 - s_speed
     if pos_l1_0 == - 1920:
          pos_l1_0 = 1920
     elif pos_l1_1 == - 1920:
          pos_l1_0 = 1920
     screen.blit(land_1,(pos_l1_0, hight_land_1))
     screen.blit(land_1,(pos_l1_1, hight_land_1))

     # 2nd
     pos_l0_0 = pos_l0_0 - s_speed/2
     pos_l0_1 = pos_l0_1 - s_speed/2
     if pos_l0_0 == - 1920:
          pos_l0_0 = 1920
     elif pos_l0_1 == - 1920:
          pos_l0_0 = 1920
     screen.blit(land_0,(pos_l0_0, hight_land))
     screen.blit(land_0,(pos_l0_1, hight_land))
     pg.display.update()

我希望第一层快速滚动,第二层(背景缓慢滚动),我在前20秒内进行伪装,但是此后它是随机的:一层消失,或者一层发白,太奇怪了……

1 个答案:

答案 0 :(得分:1)

滚动的 land 可以想象成一排排的瓷砖。如果要在特定位置绘制背景,则必须通过模(%)运算符来计算图块相对于屏幕的位置。第二部分拼贴的位置偏移了陆地表面的宽度(例如land_0.get_width())。

这意味着为每个背景 land 定义一个位置(偏移)就足够了,因为第二个位置可以通过地形的宽度来计算。

编写一个函数,将陆地移动一定的偏移量(speed),绘制 land 表面并返回新位置:

def drawLand(pos, height, speed, land):
    width = land.get_width()
    pos = (pos + speed) % width
    screen.blit(land, (pos, height))
    pos_2 = pos + width if pos < 0 else pos - width
    screen.blit(land, (pos_2, height))
    return pos

在应用程序的主循环中为每个 land 调用函数:

pos_l0, hight_land = 2, 500
pos_l1, hight_land_1 = -1000, 400
s_speed = 2
while a:

    # [...]

    screen.blit(bg,(0, 0))
    pos_l1 = drawLand(pos_l1, hight_land_1, -s_speed, land_1)
    pos_l0 = drawLand(pos_l0, hight_land, -s_speed // 2, land_0)
    pg.display.update()