0

I'm following this tutorial, https://phaser.io/examples/v2/sprites/extending-sprite-demo-2, and I have the following:

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

The sprites don't spin and the update function doesn't log to the console any more. How do I fix this? Thanks.

1 Answer 1

3

There are two bugs in your code.

First, in your MonsterBunny constructor you are adding 2 sprites not 1. The var test = game.add.sprite.. shouldn't be there, because a sprite is already added by calling the sprite constructor Phaser.Sprite.call.

Second, in the call to the Phaser.Sprite constructor you forgot to add the key parameter, so which image to use, in your case it's called 'player'. Because of this, it actually adds a sprite but it doesn't display at all.

So, something like this should work:

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);
};
Sign up to request clarification or add additional context in comments.

2 Comments

But if do like that we only create one sprite. I modify example to create multi sprite in a Object
@BdR is correct with his code. Here's a corrected Fiddle that I did separately, so it doesn't include the anchor modification: jsfiddle.net/31odrwLz

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.