Sonolus Wiki

03. 初始化

在本章中,我们将学习初始化模式的概念,它是如何在引擎中使用的。

初始化模式

关卡通常具有一些需要计算并提供给其它实体使用的全局值。

举个例子,舞台区域可能会根据屏幕纵横比而变化——我们并不需要每次获取这个值的时候都计算一遍;而是在一开始计算一次,并将计算结果存储在全局块中,例如关卡数据。

初始化模式就是为了实现这样一个目标:具有初始化原型的实体将始终是首个唯一生成的实体,并在它认为合适的时间内进行初始化工作。其他实体只会在初始化实体消失后生成。

项目模板中自带 Initialization 文件,其中实现了初始化模式,我们来看一下。

生成逻辑

我们初始化实体的生成逻辑相当简单:我们只需要确保它是第一个生成,并且是立即生成的。

为了让它成为第一个生成的实体,我们只需要让它的spawnOrder回调返回一个低于任何其他实体值的值。

在这种情况下,我们可以使用0

export class Initialization extends Archetype {
    // ...

    spawnOrder() {
        return 0
    }

    // ...
}
export class Initialization extends Archetype {
    // ...

    spawnOrder() {
        return 0
    }

    // ...
}

初始化负载

初始化负载可以放在实体生命周期的任何地方,通常是在preprocessupdateSequential回调中。

对于本指南中的引擎,我们没有任何初始化工作要在updateSequential中执行。

preprocess将用于在关卡开始前执行负载,通常包含设置变换、游戏 UI、得分、生命等。由于项目模板附带设置菜单 UI 的代码,因此我们可以退出开发关卡。

export class Initialization extends Archetype {
    preprocess() {
        ui.menu.set({
            anchor: screen.rect.lt.add(new Vec(0.05, -0.05)),
            pivot: { x: 0, y: 1 },
            size: new Vec(0.15, 0.15).mul(ui.configuration.menu.scale),
            rotation: 0,
            alpha: ui.configuration.menu.alpha,
            horizontalAlign: HorizontalAlign.Center,
            background: true,
        })
    }

    // ...
}
export class Initialization extends Archetype {
    preprocess() {
        ui.menu.set({
            anchor: screen.rect.lt.add(new Vec(0.05, -0.05)),
            pivot: { x: 0, y: 1 },
            size: new Vec(0.15, 0.15).mul(ui.configuration.menu.scale),
            rotation: 0,
            alpha: ui.configuration.menu.alpha,
            horizontalAlign: HorizontalAlign.Center,
            background: true,
        })
    }

    // ...
}

销毁

使初始化实体销毁与使任何其他实体销毁相同:通过将this.despawn设置为true ,该实体将被安排在当前帧结束时消失。

在这种情况下,销毁是在updateSequential中完成的。

export class Initialization extends Archetype {
    // ...

    updateSequential() {
        this.despawn = true
    }
}
export class Initialization extends Archetype {
    // ...

    updateSequential() {
        this.despawn = true
    }
}