4

I have a problem updating a sprite.

I created a function to change clothes. This should work like:

// Something like this.
pet = pet_with_hat

There is code at https://github.com/futer/pandachii in in js/main.js, line 387.

When I write this:

this.pet = this.game.add.sprite(90,90, 'pet_black_hat')

There is an error:

 Uncaught TypeError: Cannot read property 'health' of undefined
 GameState.update @ main.js:194
 Phaser.StateManager.update @ phaser.js:16628
 Phaser.Game.update @ phaser.js:23092
 Phaser.RequestAnimationFrame.updateRAF @ phaser.js:41421
 _onLoop @ phaser.js:41407

How do I change the sprite image for this pet to another?

I will be grateful.

3 Answers 3

14

For Phaser 3 you can use setTexture:

carSprite.setTexture('tank')
9

The problem is you're replacing the existing this.pet with a new Phaser.Sprite, which then doesn't have any of the custom properties you set.

For Phaser 2:

You can use loadTexture() to replace the image used for the pet sprite.

this.pet.loadTexture('pet_black_hat');

For Phaser 3:

You can use setTexture() to replace the image used for the pet sprite.

this.pet.setTexture('pet_black_hat');
3
  • 1
    I'd also highly recommend updating the version of Phaser that you use. Some of the functionality is now deprecated in certain browsers, and you'd be missing out on performance improvements. Having gone through a number of tutorials, the number of breaking changes is generally relatively small, and they're easy to find solutions to when they do occur. Apr 14, 2016 at 3:49
  • Aww... That is so simply solve :( Thanks you dude very much :) Apr 14, 2016 at 8:25
  • 1
    Also another tip: you are using a lot of small sprite files, which could make loading and performance slower. I'd recommend using something like Leshy SpriteSheet Tool to put them all into one single file, save the sprite-map as a JSON-TP-Hash, and then use Phaser.Atlas to load the sprites.
    – BdR
    Apr 14, 2016 at 15:22
3
  • If you've added the new image using scene.add.image(...) then you can use, carSprite.setTexture('tank')

  • If you want to select a different sprite in the same texture atlas that you loaded with scene.load.atlas(...), then you can call carSprite.setFrame('tank')

  • If you want to select a sprite in a completely different texture atlas, then you can call, carSprite.setTexture('newTextureAtlasKey', 'tank')

Hope this helps.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.