【问题标题】:Pygame scrolling background bugPygame滚动背景错误
【发布时间】:2021-10-07 18:16:20
【问题描述】:

我正在尝试在按下按键时在 pygame 中制作背景滚动效果。

import pygame
from pygame import *
import os

pygame.init()

WIDTH, HEIGHT = 472, 708

WIN = pygame.display.set_mode((WIDTH, HEIGHT))

FPS = 60

BG = pygame.image.load(os.path.join('images', 'BG.jpg'))
BG = pygame.transform.scale(BG, (WIDTH, HEIGHT))

class Background(object):
    def __init__(self, win, image):
        self.win = win
        self.image = image
        self.bgY = 0
        self.bgY2 = BG.get_height()
        self.bgY3 = BG.get_height() * -1

    def draw(self):
        self.win.blit(self.image, (0, self.bgY))
        self.win.blit(self.image, (0, self.bgY2))
        self.win.blit(self.image, (0, self.bgY3))
        pygame.display.update()

    def bg_movement(self):
        keys = pygame.key.get_pressed()
        if keys[K_w]:
            self.bgY += 2
            self.bgY2 += 2
            self.bgY3 += 2
        if keys[K_s]:
            self.bgY -= 2
            self.bgY2 -= 2
            self.bgY3 -= 2
        if self.bgY < self.image.get_height() * -1:
            self.bgY = self.image.get_height()
        if self.bgY2 < self.image.get_height() * -1:
            self.bgY2 = self.image.get_height()
        if self.bgY3 < self.image.get_height() * -1:
            self.bgY3 = (self.image.get_height() * -1)

player = Background(WIN, BG)

def main():
    clock = pygame.time.Clock()
    running = True
    while running:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        
        player.draw()
        player.bg_movement()

    pygame.quit()

if __name__ == '__main__':
    main()

当我按下 S 键时,背景会正常滚动。但是当我按 W 键一会儿时,背景开始留下痕迹。

This is the actual image used in the game.

This is the screenshot showing the bug in the game. The image leaves a trail.

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    使用取模 (%) 运算符计算背景的位置。 % 运算符计算除法提醒:

    class Background(object):
        def __init__(self, win, image):
            self.win = win
            self.image = image
            self.bgY = 0
    
        def draw(self):
            self.win.blit(self.image, (0, self.bgY - self.image.get_height()))
            self.win.blit(self.image, (0, self.bgY))
            self.win.blit(self.image, (0, self.bgY + self.image.get_height()))
            pygame.display.update()
    
        def bg_movement(self):
            keys = pygame.key.get_pressed()
            if keys[K_w]:
                self.bgY = (self.bgY + 2) % self.image.get_height()
            if keys[K_s]:
                self.bgY = (self.bgY - 2) % self.image.get_height()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多