pygame-KidsCanCode系列jumpy-part18-背景滾動


上回繼續,之前的游戲背景過於單調,今天加幾朵白雲的背景效果。

要點:

1. 白雲要有大有小,盡量模擬出遠近層次的效果。

2. 兔子向上跳時,(背景)白雲也要相應的滾動,但是為了視覺效果,速度要低於檔板的速度(比如:1/2 or 1/3)。

3. 白雲要放在最下層(即:Layer值最低),否則就會把其它物體擋住。

 

先定義白雲:

# 白雲背景
class Cloud(pg.sprite.Sprite):
    def __init__(self, game, x, y, scale=1):
        pg.sprite.Sprite.__init__(self)
        self.game = game
        self.image = self.game.spritesheet.get_image("cloud.png", scale)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

  
main.py中初始化:

    def new(self):
        self.score = 0
        self.all_sprites = pg.sprite.LayeredUpdates()
        ...
        self.clouds = pg.sprite.Group()
        ...

        # 初始化生成白雲
        for i in range(2, 4):
            scale = random.choice([2.5, 3.0, 3.5, 4.0, 4.5])
            c = Cloud(self, random.randrange(0, WIDTH), random.randrange(-100, HEIGHT), scale)
            self.all_sprites.add(c, layer=CLOUD_LAYER)
            self.clouds.add(c)

       ...

其中常量CLOUD_LAYER的值,仍在settings.py中定義:

# layer
PLAYER_LAYER = 4
MOB_LAYER = 3
PLATFORM_LAYER = 1
POWERUP_LAYER = 2
CLOUD_LAYER = 0

  

update時,更新白雲的滾動效果,以及數量不足時,自動補足:

    def update(self):
        self.all_sprites.update()

       ...

        if self.player.rect.top < HEIGHT / 4:
            self.player.pos.y += max(abs(self.player.vel.y), 2)
           ...
            # 屏幕滾動時,白雲也自動滾動(注:為了視覺效果更自然,滾動速度是擋板的1半)
            for cloud in self.clouds:
                cloud.rect.top += max(abs(self.player.vel.y) // 2, 2)
                if cloud.rect.top > HEIGHT:
                    cloud.kill()

       ...

        # cloud不夠時,自動補充
        while len(self.clouds) <= 3 and self.player.rect.bottom < HEIGHT:
            scale = random.choice([2.5, 3.0, 3.5, 4.0, 4.5])
            c = Cloud(self, random.randrange(0, WIDTH), random.randrange(-200, -50), scale)
            self.all_sprites.add(c, layer=CLOUD_LAYER)
            self.clouds.add(c)

  

示例源碼:https://github.com/yjmyzz/kids-can-code/tree/master/part_18


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM