Skip to content

awake 事件 ​

Phaser Editor v5 · 英文原文

我们提议使用 Phaser 事件来实施用户组件行为。 但是, Phaser 中提供的事件还不够。 当创建组件时, 所有属性都设置为默认值。 然后, 您设定每个属性的值。 然而, 您也许想要在所有属性设定后执行自定义初始化程序 。

查看 Phaser事件, 您可以在第一幕的更新中完成它。 这意味着你可以监听一次 ** UPDATE ** 事件并运行初始化程序。 它可能在许多情况下有效。 但也许, 您想要在设定所有属性之后, 在游戏开始更新循环之前运行此程序 。

为此,scene compiler生成出自定义事件——scene-awake事件——的代码,就在它生成产生场景中对象的代码之后,它们的所有属性都设定了: . .. code:

javascript
// code generated by the compiler:

editorCreate() {

    // creates the game object
    const dino = this.add.image(400, 240, "FufuSuperDino");

    // creates the PushOnClick component
    const dinoPushOnClick = new PushOnClick(dino);

    // sets the component's properties
    dinoPushOnClick.pushDelay = 500;

    // emit the scene-awake event, after all objects are created
    // and all properties are set
    dino.emit("scene-awake");
}

当您执行一个组件时, 您可以在 scene-ake 事件上注册一个监听器 :

javascript
class PushOnClick {

    constructor(gameObject) {
        ...

        this.gameObject = gameObject;

        gameObject.scene.events.once("scene-awake", () => {

            // I register a "pointerdown"
            // event for "animating" the game object
            // with a push effect

            // I set a pixel perfect handler
            // with certain alpha-tolerance
            const handler = this.scene.input
                .makePixelPerfect(this.alphaTolerance);


            this.gameObject.setInteractive(handler)
                .on("pointerdown", () => {
                    // animate the object with the push effect
                    this.gameObject.scene.add.tween(...);
                });
        });
    }

    /** @type {number} **/
    alphaTolerance = 100;
}

在A base class for your components部分,我们解释如何对所有组件使用一个通用的超级。它简化了Phaser事件的听觉,也包括了scene-awake事件。所以你可以以这种方式重写先前的PushOnClick组件:

javascript
class PushOnClick extends UserComponent {

    constructor(gameObject) {
        super(gameObject);
    }

    awake() {

        // Instead of registering a scene-awake event listener
        // you can override this method.

        ...

        this.gameObject.setInteractive(...)
                .on("pointerdown", ...);
        ...
    }
    ...
}

scene-awake事件以场景的editorCreate()方法释放。所以,如果你创建了新的组件,这个组件会听scene-awake事件,那么你应该手动释放该事件:

javascript
const comp = new PushOnClick(someSprite);
comp.alphaTolerance = 50;
// emit the awake event so the component can be notified
this.events.emit("scene-awake");

游戏后期的Emting scene-awake事件是安全的,因为组件和预制体在他们一生中只处理过一次这一事件.

预告片亦收听scene-awake事件. Learn more about it.


社区翻译