这在Phaser游戏JS中

时间:2015-05-07 13:41:58

标签: javascript phaser-framework

所以我最近开始学习JS,现在尝试使用Phaser来制作游戏。 在下面的代码中,

1-是作者通过使用“this”引用mainState? 2-没有为鸟类定义的变量。它在哪里存储数据呢?

// Initialize Phaser, and creates a 400x490px game
var game = new Phaser.Game(400, 490, Phaser.AUTO, 'gameDiv');

// Creates a new 'main' state that will contain the game
var mainState = {

    // Function called first to load all the assets
    preload: function() { 
        // Change the background color of the game
        game.stage.backgroundColor = '#71c5cf';

        // Load the bird sprite
        game.load.image('bird', 'assets/bird.png');  

        // Load the pipe sprite
        game.load.image('pipe', 'assets/pipe.png');      
    },

    // Fuction called after 'preload' to setup the game 
    create: function() { 
        // Set the physics system
        game.physics.startSystem(Phaser.Physics.ARCADE);

        // Display the bird on the screen
        this.bird = this.game.add.sprite(100, 245, 'bird');

        // Add gravity to the bird to make it fall
        game.physics.arcade.enable(this.bird);
        this.bird.body.gravity.y = 1000; 

        // Call the 'jump' function when the spacekey is hit
        var spaceKey = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
        spaceKey.onDown.add(this.jump, this); 

        // Create a group of 20 pipes
        this.pipes = game.add.group();
        this.pipes.enableBody = true;
        this.pipes.createMultiple(20, 'pipe');  

        // Timer that calls 'addRowOfPipes' ever 1.5 seconds
        this.timer = this.game.time.events.loop(1500, this.addRowOfPipes, this);           

        // Add a score label on the top left of the screen
        this.score = 0;
        this.labelScore = this.game.add.text(20, 20, "0", { font: "30px Arial", fill: "#ffffff" });  
    },

2 个答案:

答案 0 :(得分:3)

您发布的代码中的

指的是您推断的mainState。使用this.valueName在mainState对象上创建一个新值。

有关此关键字的详细信息及其在不同位置使用时的含义,请参阅this link。链接页面中的此示例与您的代码相关:

var o = {
  prop: 37,
  f: function() {
    return this.prop;
  }
};

console.log(o.f()); // logs 37

它像往常一样存储数据,出于所有意图和目的,它执行的功能与正常添加函数外的其他值相同。并且可以使用mainState.bird访问。

var mainState = {
    bird : game.addBird(...)
}

答案 1 :(得分:3)

  1. 是的,this对象的函数中的mainState关键字指向mainState对象本身。

  2. bird变量在mainState对象本身上定义:

    // Display the bird on the screen
    this.bird = this.game.add.sprite(100, 245, 'bird');