开发者问题收集

Phaser // Javascript // Player 未定义

2017-01-11
4196

一切正常,除了在 update 函数中,当我放回 var player 时,它无法识别它:

"Uncaught ReferenceError: player is not defined"

(我也不确定动画)(马里奥是玩家,这是一个马里奥级别)

这是我的代码:

var SandBox = {

    preload:function(){

        //this.game
        console.log("preload Sand Box");

        this.game.load.image('platform', 'assets/platform.png');
        this.game.load.spritesheet('mario', 'assets/mario.png', 32, 32 , 12);
        this.game.load.image('coinbox', 'assets/coinbox.png');
    },

    create:function(){
        console.log("create Sand Box");

        var imageHeight = this.game.cache.getImage("platform").height;
        this.game.physics.startSystem(Phaser.Physics.ARCADE);

        var worldHeight = this.game.world.height;


        var ground = this.game.add.sprite(0, worldHeight - imageHeight, 'platform');
        var platform = this.game.add.sprite(250, 285, 'platform');
        var platform = this.game.add.sprite(-250, 145, 'platform');
        var platform = this.game.add.sprite(280, 285, 'coinbox');
        var player = this.game.add.sprite(32, 100, 'mario');

        this.game.physics.enable(ground);
        this.game.physics.enable(platform);
        this.game.physics.arcade.enable(player);

        player.frame = 5;
        ground.body.immovable = true;
        platform.body.immovable = true;        
        player.body.bounce.y = 0.2;
        player.body.gravity.y = 300;
        player.body.collideWorldBounds = true;


        player.animations.add('left', [0, 1, 2, 3], 10, true);
        player.animations.add('right', [5, 6, 7, 8], 10, true);

    },

    update:function(){
        console.log("update Sand Box");
        this.game.physics.arcade.enable(player);

        var hitPlatform = this.game.physics.arcade.collide(player, ground); // << THESE FUNCTIONS
    }


}
1个回答

代码片段中变量 player 作用域 位于其所在函数的本地。可以将 player 的声明(使用 var )移到 sandbox 对象之外:

var player;
var sandbox = {
    create: function() {
         //... skipping lines ...
         player = this.game.add.sprite(32, 100, 'mario');
    }, 
    Update: function() {
          //use player here
          var hitPlatform = this.game.physics.arcade.collide(player, ground); // << THESE FUNCTIONS

    }
};

或者使其成为对象的一部分:

 var sandbox = {
        create: function() {
             //... skipping lines ...
             this.player = this.game.add.sprite(32, 100, 'mario');
      }, 
      Update: function() {
            //... skipping lines ...
            //use this.player here
            var hitPlatform = this.game.physics.arcade.collide(this.player, ground);
       }
 };
Sᴀᴍ Onᴇᴌᴀ
2017-01-11