【问题标题】:Phaser - Create player objectPhaser - 创建玩家对象
【发布时间】:2017-03-03 01:59:20
【问题描述】:

我正在关注本教程,https://phaser.io/examples/v2/sprites/extending-sprite-demo-2,我有以下内容:

MonsterBunny = function (game, x, y, rotateSpeed) {
    Phaser.Sprite.call(this, game, x, y);
    var test = game.add.sprite(x, y, 'player');
    test.rotateSpeed = rotateSpeed;
};
MonsterBunny.prototype = Object.create(Phaser.Sprite.prototype);
MonsterBunny.prototype.constructor = MonsterBunny;
MonsterBunny.prototype.update = function() {
    this.angle += this.rotateSpeed;
    console.log('a');
};

var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create });

function preload() {
    game.load.crossOrigin = 'anonymous';
    game.load.image('player', 'http://examples.phaser.io/_site/images/prize-button.png');
}

function create() {
    var wabbit = new MonsterBunny(game, 0, 100, 1);
    var wabbit2 = new MonsterBunny(game, 150, 100, 0.5);
}

JSFiddle

精灵不再旋转,update 函数不再登录到控制台。我该如何解决?谢谢。

【问题讨论】:

    标签: javascript phaser-framework


    【解决方案1】:

    您的代码中有两个错误。

    首先,在您的 MonsterBunny 构造函数中,您要添加 2 个精灵而不是 1 个。var test = game.add.sprite.. 不应该存在,因为通过调用精灵构造函数 Phaser.Sprite.call 已经添加了精灵。

    其次,在调用Phaser.Sprite 构造函数时,您忘记添加key 参数,所以要使用哪个图像,在您的情况下它被称为'player'。因此,它实际上添加了一个精灵,但它根本不显示。

    所以,这样的事情应该可以工作:

    MonsterBunny = function (game, x, y, rotateSpeed) {
        // call sprite constructor to create sprite
        Phaser.Sprite.call(this, game, x, y, 'player');
    
        // set extra variables
        this.rotateSpeed = rotateSpeed;
        this.anchor.setTo(0.5, 0.5); // for centered rotation
    
        // add sprite to game world
        game.add.existing(this);
    };
    

    【讨论】:

    • 但是如果这样做我们只创建一个精灵。我修改示例以在对象中创建多个精灵
    • @BdR 的代码是正确的。这是我单独做的一个更正的 Fiddle,所以它不包括 anchor 修改:jsfiddle.net/31odrwLz
    猜你喜欢
    • 2020-12-07
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    • 2022-01-17
    相关资源
    最近更新 更多