Phaser Javascript游戏,这个关键字和游戏状态

时间:2017-02-05 12:47:40

标签: javascript

我刚刚开始使用Phaser创建Javascript游戏,并对“this”关键字有疑问。

  • 是否指当前状态(rainState)?

  • 我假设 this.emitter = this.game.add.emitter(100,0,400); 在存储发射器对象的rainState对象上创建一个emitter属性?

  • 游戏是国家的财产吗?为什么写 this.game.add.emitter 而不是 this.add发射器

// --------------------------------------------- ----

     var Smash = Smash || {};

    Smash.rainState = {
        create: function() {
            this.emitter = this.game.add.emitter(this.game.world.centerX, 0, 400);

            this.emitter.width = this.game.world.width;
            this.emitter.angle = 30;
            this.emitter.makeParticles('particle');

            this.player = new Smash.Player(this.game, 100, 300, 'player');

            this.intro0();       
        },

        intro0: function() {
          this.player.animations.play("run", 9, true);
        },
    };

1 个答案:

答案 0 :(得分:1)

  

这是指当前状态(rainState)吗?

答案取决于它的调用方式。

如果它被称为rainState对象的方法,则上下文(this)将被设置为rainState对象:

Smash.rainState.create();

使用callapplybind,您可以传入您想要的任何范围作为参数:

Smash.rainState.create.call(foo); //immediately invoked
Smash.rainState.create.apply(foo); //immediately invoked
var bar = Smash.rainState.create.bind(foo); //reference to a newly created bound function
  

我假设this.emitter = this.game.add.emitter(100,0,400);在存储发射器对象的rainState对象上创建一个emitter属性?

当您为this.emitter分配值时,系统会将其添加为对象rainState的属性。

Smash.rainState = {
    create: function() {
        console.log(Smash.rainState.emitter); //undefined
        this.emitter = this.game.add.emitter(this.game.world.centerX, 0, 400);
        console.log(Smash.rainState.emitter); //[object Object]
    },      
};
  

游戏是国家的财产吗?为什么写this.game.add.emitter而不是this.add发射器

根据您提供的代码,game似乎不是rainState的方法或属性。此外,this.add不是object类型的内置函数。除非game已作为rainState的属性添加到其他位置,否则您需要以其他方式引用它。

全局:

var game = new Phaser.Game();

var Smash = Smash || {};

Smash.rainState = {
    create: function() {
         this.emitter = game.add.emitter(this.game.world.centerX, 0, 400);

作为从上下文中存在game的地方传入的参数:

Smash.rainState = {
    create: function(game) {
         this.emitter = game.add.emitter(this.game.world.centerX, 0, 400);
    }
}

//a context where game is a property
{
    this.game = new Phaser.Game();   

    Smash.rainState.create(this.game);
}

Phaser有一些特定的设置,围绕如何在不同的上下文中引用game类的Phaser.Game实例化:

  

“Via”:如果某个类在via列中有一个条目,则表示您可以通过本地引用快速访问它。即您可以通过任何州的this.camera控制相机,如果游戏已全局定义,则可以通过game.camera控制相机。

这意味着如果您在全局范围内(任何game之外)初始化了{}实例,那么您应该能够全局调用它。在代码中查找类似的内容并确保它不在另一个函数或对象中:

var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render });
相关问题