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
作者:菩提树下的杨过
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
浙公网安备 33010602011771号