未定义阶段器// Javascript //播放器

2w2cym1i  于 2023-01-24  发布在  Java
关注(0)|答案(1)|浏览(95)

一切正常,除了在 * update * 函数中,当我放回var player时,它无法识别它:
"未捕获的引用错误:未定义播放器"
(我也不确定动画)(马里奥是玩家,这是马里奥级别)
下面是我的代码:

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
    }

}
t9aqgxwy

t9aqgxwy1#

代码片段中变量playerscope是它所在函数的局部变量。可以将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);
       }
 };

相关问题