Jump to content

General functionality and inheritance


DerDree
 Share

Recommended Posts

So my current project reached a point where I see that multiple prefabs use the same functionality. For example friends and enemies both have identical move functionality. What is the preferred way to handle such common functionality in phaser?

 

I know there is the monsterBunny example to show class inheritance. But that only shows inheritance of the sprite class which I'm using already for my prefabs.

 

How can I achive even more inheritance? So I want for example a human class with general functionality like moving and then a enemy class with special functions and a specific sprite.

 

I tried achieving this but could not get constructor parameters passed to the human as parent and create a new human for each child so that they dont use the same human class and share parent attributes.

Link to comment
Share on other sites

My general rule is you never refactor something just because you wrote it twice. I always put my threshold for refactoring to 3 or more. Flexibility is valuable!

 

That aside I'm assuming you have hard a look and really decided you need to refactor. This is how I would go about it.

BasePlayer = function (game, x, y, key) {    Phaser.Sprite.call(this, game, x, y, key);};BasePlayer.prototype = Object.create(Phaser.Sprite.prototype);BasePlayer.prototype.constructor = BasePlayer;BasePlayer.prototype.specialMovement = function (arg1, arg2, ... ..) {    // ...do your thing!};Human = function (game, x, y) {    BasePlayer.call(this, game, x, y, 'human');};Human.prototype = Object.create(BasePlayer.prototype);Human.prototype.constructor = Human;Human.prototype.laugh = function (arg1, arg2, ... ..) {    // ...ha ha ha ha ha};Enemy = function (game, x, y) {    BasePlayer.call(this, game, x, y, 'enemy');};Enemy.prototype = Object.create(BasePlayer.prototype);Enemy.prototype.constructor = Enemy;Enemy.prototype.laugh = function (arg1, arg2, ... ..) {    // ...mwaha ha ha mwaha ha};

Both Human and Enemy are capable of 'special movement' because they inherit from BasePlayer.

 

And Human and Enamy can also have their own functions as well!

Link to comment
Share on other sites

  • 5 months later...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...