我正在尝试使用 pygame 创建一个游戏,并尝试为其添加背景(我使用了 YouTube 视频中的一些代码,但这不起作用)。我也不明白代码的含义。我的意思是背景确实会移动,但当旧背景尚未离开屏幕时,它会自动在屏幕中间添加新版本的背景:
class Background:
def __init__(self, x, y, picture):
self.xpos = x
self.ypos = y
self.picture = picture
self.rect = self.picture.get_rect()
self.picture = pygame.transform.scale(self.picture, (1280, 720))
def paste(self, xpos, ypos):
screen.blit(self.picture, (xpos, ypos))
def draw(self):
screen.blit(self.picture, (self.xpos, self.ypos))
while True:
background=pygame.image.load("C:/images/mars.jpg").convert_alpha()
cliff = Background(0, 0, background)
rel_x = x % cliff.rect.width
cliff.paste(rel_x - cliff.rect.width, 0)
if rel_x < WIDTH:
cliff.paste(rel_x, 0)
x -= 1
这就是我的背景目前发生的情况 [![我的问题是什么样的][1]][1]
[![我希望背景像这样移动][2]][2]
这就是我想要的背景(请忽略它是我唯一能找到的标志)
我现在发现了真正的问题是什么
最佳答案
如果你想要一个连续重复的背景,那么你必须绘制背景两次:
您必须知道屏幕的尺寸。高度背景图像的大小应与屏幕的高度相匹配。背景的宽度可以不同,但至少应该是窗口的宽度(否则背景必须绘制两次以上)。
bg_w, gb_h = size
bg = pygame.transform.smoothscale(pygame.image.load('background.image'), (bg_w, bg_h))
背景可以想象为一排无尽的瓷砖。
如果你想在某个位置 pos_x
绘制背景,那么你必须通过模 (%
) 运算符计算图 block 相对于屏幕的位置。第二个图 block 的位置按背景宽度移动 (bg_w
):
x_rel = pos_x % bg_w
x_part2 = x_rel - bg_w if x_rel > 0 else x_rel + bg_w
最后,背景必须被blit两次,以填充整个屏幕:
screen.blit(bg, (x_rel, 0))
screen.blit(bg, (x_part2, 0))
您可以通过以下示例程序来测试该过程。背景可以分别移动<- ->
import pygame
pygame.init()
size = (800,600)
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
bg_w, bg_h = size
bg = pygame.transform.smoothscale(pygame.image.load('background.image'), (bg_w, bg_h))
pos_x = 0
speed = 10
done = False
while not done:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
allKeys = pygame.key.get_pressed()
pos_x += speed if allKeys[pygame.K_LEFT] else -speed if allKeys[pygame.K_RIGHT] else 0
x_rel = pos_x % bg_w
x_part2 = x_rel - bg_w if x_rel > 0 else x_rel + bg_w
screen.blit(bg, (x_rel, 0))
screen.blit(bg, (x_part2, 0))
pygame.display.flip()
另请参阅How to make parallax scrolling work properly with a camera that stops at edges pygame
关于python - 在pygame中使背景横向移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55050166/