Complex Objects – Phaser

Most of the time when we are writing games in Phaser we are using simple objects like a sprite, text, or a button. I really enjoy writing in Phaser, but sometimes I miss when I use to make flash games and I could create a lot of different elements within a class. While I can not do exactly the same thing with Phaser, what can be done is to create a function to make a complex object. A complex object is simply my phrase that I use to describe a group containing child elements. In this way, I can basically get the same result that I did in flash.

In this example below I have written a function that makes a button object, which in this case is not the buttons built into the Phaser framework, but a group that contains a text field and a sprite back. This is useful in situations where you don’t know what buttons you’ll need, so you can just throw in a new button with 1 line of code.

I’ve also just recently used this technique for a couple of games I’m writing for children learning the alphabet, with letters inside spaceships in one game and letters in bubbles in another. I simply built a makeBubble or makeShip function and looped through the alphabet to create everything I needed.

To use this technique we need to do 4 things

  1. Create a function with parameters of what we what to style (text, color, size, frame)
  2. Make child elements to reflect those style choices(sprites, text fields)
  3. Make a group and place those elements inside
  4. return that group as the object

I have done this with the makeButton function and have created the buttons in the create function.


var StateMain = {

    preload: function () {

    create: function () {
       var btnYes=this.makeButton("YES",1);

       var btnNo=this.makeButton("NO",0);

    	//create the back for the button
    	var back=game.add.image(0,0,"colors");

    	//create the label for the button
    	//and set the text to the text parameter passed down
    	var label=game.add.text(0,0,text);


    	//create the group

    	//add the sprite and the label to the group

    	//groups can not take input so we need to add the
    	//listener for the click 
    	//return the group as the button
    	return buttonGroup;

    	//since the target is the sprite
    	//we get the parent of the target
    	var group=target.parent;
    	//the label is the second child we added to the
    	//group so we can find it at index 1
    	//the back sprite is found at index 0
    	var label=group.getChildAt(1);


    update: function () {



The post Complex Objects – Phaser appeared first on William Clarkson.

Leave a Comment