javascript - 这在 Phaser 游戏 JS 中

标签 javascript phaser-framework

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

1- 作者是否使用“this”来指代 mainState? 2- 没有为 bird 定义变量。那么它在哪里存储数据??

// 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" });  
    },

最佳答案

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

参见 this link有关 this 关键字的更多信息以及它在不同地方使用时所指的内容。链接页面中的这个示例与您的代码相关:

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

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

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

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

关于javascript - 这在 Phaser 游戏 JS 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30102884/

相关文章:

javascript - 如何清除/重置react.js表单中的输入数据?

javascript - 如何获取表中 TR 中 TD 的大陆值?

javascript - 如何在 jQuery 中选择具有 name 属性的元素?

javascript - 移动设备的最大图像/SpriteSheet 尺寸 Phaser.js

javascript - 在 AJAX 函数内的 Phaser 中循环添加 Sprite

javascript - 虚拟操纵杆边框椭圆形而不是圆形

javascript - 音频输入移相器?

javascript - Knockout.js 复选框的双向绑定(bind)不起作用

javascript - Angular Material md-contact-chips 自动完成问题

javascript - 加载函数中的phaser js undefined variable