pygame飞机大战用精灵组(sprite)的层(layer)编写(三)BOSS动起来了

接下来,让BOSS舞动起来。

前面的日记里的代码,可以看到BOSS悬浮在空中,没有生机。这篇日记,就让BOSS动起来,至少能走两步。

sprite 的 update函数,更新坐标是最好的。

先让BOSS左右移动吧。

只要添加一个速度,在加上一个边界判断就完成了。so easy!

# 飞机速度

self.x_speed = 2

左右移动,只是改变了x 的坐标而已,一个变量就够了。

update里添加

        self.rect.x += self.x_speed
        if self.rect.x + self.rect.width > SCENEWIDTH or self.rect.x < 0:
            self.x_speed = -self.x_speed
            self.rect.x += self.x_speed

运行一下,BOSS开始左右移动了。

让BOSS进行类似光线的反射方式移动,加个y 坐标的移动,稍微来些判断就能实现

            if self.rect.x + self.rect.width > SCENEWIDTH or self.rect.x < 0:
                self.x_speed = -self.x_speed
            if self.rect.y + self.height > SCENEHEIGHT  or self.rect.y < 0:
                self.y_speed = -self.y_speed
            self.rect.x += self.x_speed
            self.rect.y += self.y_speed

完整代码如下: boss.py

from setting import *
from animation import *


class BossPlane(pygame.sprite.Sprite):
    def __init__(self):
        self._layer = 2
        self.groups = allgroup, bossgroup
        pygame.sprite.Sprite.__init__(self, self.groups)
        #设置飞机动态图像
        self.animation = Animation()
        self.images = self.animation.load_images('images/boss/', 0, 10, '.png')
        self.image = self.images[1]
        self.mask = pygame.mask.from_surface(self.image)
        # 飞机矩形
        self.rect = self.image.get_rect()
        self.x_speed = 2
        self.y_speed = 2
        #默认移动方式
        self.motion_type = 1

    def update(self):
        #更新飞机当前图像
        self.image = self.animation.get_current_image()
        if self.motion_type == 0:
            if self.rect.x + self.rect.width > SCENEWIDTH or self.rect.x < 0:
                self.x_speed = -self.x_speed
            # self.rect.y += self.y_speed
            self.rect.x += self.x_speed
        elif self.motion_type == 1:
            if self.rect.x + self.rect.width > SCENEWIDTH or self.rect.x < 0:
                self.x_speed = -self.x_speed
            if self.rect.y + self.rect.height > SCENEHEIGHT  or self.rect.y < 0:
                self.y_speed = -self.y_speed
            self.rect.x += self.x_speed
            self.rect.y += self.y_speed

加上点随机函数,两个方向的速度也随机,就能让BOSS舞动更妖娆。

例如

        if random.randint(0,50) == 1:
            self.motion_type = random.randint(0,1)
            self.x_speed = random.randint(-5,6)
            self.y_speed = random.randint(-6,5)

天知道BOSS下一步要飞哪里了。

猜你喜欢

转载自blog.csdn.net/hailler1119/article/details/88927519