Jump to content

Including Player Control Methods into an Existing Game State from a Separate File


TerryScrimsher
 Share

Recommended Posts

My current project uses game states, and I'm to the point where I have a character that can walk between different levels (states), but in every js file where my individual levels are I have all my code for player movement duplicated in each.

I'd like to make my code slimmer and more modular because I'm to the point where I'm getting some slow down/lag in chrome browsers, and I'd like to keep scaling my project and that isn't easy with all of this duplicate code in every state. For reference, the way my project is constructed is based off of this tutorial: http://www.emanueleferonato.com/2014/08/28/phaser-tutorial-understanding-phaser-states/

For example, if this were one of my level states:

var theGame = function(game){
spriteNumber = null;
number = 0;
workingButtons = true;
higher = true;
score = 0;
}
 
theGame.prototype = {
create: function(){
number = Math.floor(Math.random()*10);
spriteNumber = this.game.add.sprite(160,240,"numbers");
spriteNumber.anchor.setTo(0.5,0.5);
spriteNumber.frame = number;
var higherButton = this.game.add.button(160,100,"higher",this.clickedHigher,this);
higherButton.anchor.setTo(0.5,0.5);
var lowerButton = this.game.add.button(160,380,"lower",this.clickedLower,this);
lowerButton.anchor.setTo(0.5,0.5);
},
clickedHigher: function(){
higher=true;
this.tweenNumber(true);
},
clickedLower: function(){
higher=false;
this.tweenNumber(false);
}
}

How could I add methods to the theGame prototype object from a separate JS file? For this example, I'll like to use the clickedHigher method in a handful of different states, but I don't want to have to go through and edit it in each state. In my actually game I'm going to have up 50 different states and each time I refine my controls or add new mechanics I'd have to go through each state and copy paste.

Thanks in advance :)

Link to comment
Share on other sites

23 minutes ago, TerryScrimsher said:

I have a character that can walk between different levels (states), but in every js file where my individual levels are I have all my code for player movement duplicated in each.

Can you extract/move this code into a Player class? That will be simpler than sharing the code among states.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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