Merlin Merlin - 4 months ago 14
Javascript Question

I can't seem to access a object's prototype method in Phaser with a custom tile object. What am I doing wrong?

I am extending a basic Sprite object in Phaser to include some additional functions, mainly the ability to switch the textures with shortcut words. However, when I try to access the method, I get

"hex.switchSprite is not a function"

After some basic research, most of the answers are saying to include .prototype - however.. it's already in the method. This is the object itself that I have so far. Everything in switchSprite has been removed for testing purposes:

hexTile = function(game, x, y)
{
Phaser.Sprite.call(this, game, x, y, 'masterTileSheet', 'Gemstone_Missing');
this.scale.x = 0.75;
this.scale.y = 0.75;
this.anchor.x = 0.5;
this.anchor.y = 0.5;
}

hexTile.prototype.switchSprite = function(name)
{

}

hexTile.prototype = Object.create(Phaser.Sprite.prototype);
hexTile.prototype.constructor = hexTile;


I followed the example set out in the Phaser docs, and when I don't use switchSprite, it works:

var hex = new hexTile(game, 0, 0);
var point = calculateGrid(x,y);
hex.x = point.x;
hex.y = point.y;

gameContainer.add(hex);

//console.log(returnRandomHex());

hex.switchSprite();


The above is how I'm accessing and running it - it should be right, but for switchSprite I just get the above error.

Answer

An observation: you're overwriting your prototype:

hexTile.prototype.switchSprite = function(name)
{

}

hexTile.prototype = Object.create(Phaser.Sprite.prototype);

You set the prototype of hexTile after you added the switchSprite function to it. Try switching the order of these two statements.