Phaser Buttons

Phaser Buttons

Phaser Buttons Source Code

Button Snippets
Text Of Video:

Hi! This is William and today I’m going to show you how to put Phaser buttons into your game.

what I’ve done is I’ve copied our basic template into a buttons folder

just as I’ve done in the last few lessons

and other added some image. images/ui/. These come from the mega template and you can find all of this on WilliamClarkson.net

and I’ve also set up our brackets editor to point a to that buttons folder you just go file-> open folder

just as we did in all the other lessons. Now I’m going to edit stateMain.s and the first thing I want to do

is load that sprite sheet into the library in Phaser and we need to give it a unique ID we’ll just call it buttons

and then we give the path images/ui/ buttons-green.png

and next we need the width and height

and measure them earlier and it looks like it’s about 265 by 75 high let’s give them a try

and their 8 of them but we can just leave that number off it’s optional

now we set up a button

variable btnPlay=game.add.button

and the first thing we need to do is set an X and a Y position

and I’m going to use this.game.world.centerX

\that will give me the exact center of the screen

and just gonna put 200 px down from the top

and we use that same key buttons that we used in game.load.sprite.sheet that way Phaser knows what image to pull it from

and then we need to put a function and we’ll make that function just a moment we’ll call it clickedMe will go and place it here this.clickMe

next thing you need to pass is the scope

and it takes a long time to explain what this means but basically if you just put the word this

then you’ll be fine and next we need to put the top frame,the over frame and the down frame them

and put 0,1,0 this is corresponding to 0 for the white text and 1 for the black text

let’s make that function clickMe and I’m just a log right now that we’ve clicked it

and we will use this code at a later lesson as well use console. log(“Clicked”) so we know

that it has been pressed that the last thing we need to do is we need to put an anchor on the button.

if we don’t set the anchor everything is aligned to the top left hand corner and we want everything aligned to the center

I will show you what that means in a moment we set up the correct way first and all refreshed this and there’s a button play again

if don’t put the anchor in there it will look like this it’s left aligned to the button

so we want like that and refresh to get it back the right way far away when press it and it says clicked and that’s how you add Phaser buttons to your game.I hope you found it useful!

If you have any comments or questions put them in the comments on Youtube or contact me here and I will get back to you. Thanks for watching

Leave a Reply