You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
game.state.add('play',playState);game.state.start('play');//It also has functions useful for debugging and whatnotconsole.log("Currently at the "+game.state.getCurrentState()+" game state!");
Adjusting the game to any screen size
this.scale.scaleMode=Phaser.ScaleManager.SHOW_ALL;this.scale.pageAlignHorizontally=true;this.scale.pageAlignVertically=true;this.scale.setScreenSize(true);// setScreenSize doesn't seem to exist anymore in the current documentation
Working with globals
//Declare it outside of any functions//This way they persist through state changesgame.global={mute: false,score: 0,bestScore: 100};//Then we can change them anywheregame.global.mute=true;game.global.bestScore=game.global.score;
Using local storage
//It can only store stringslocalStorage.setItem('itemKey','myContent');//You can store entire objects by doing this:localStorage.setItem('myObject',JSON.stringify(myObject));//Then you just get the string you stored!localStorage.getItem('itemKey');
//Setting it to a nice, greyish bluegame.stage.backgroundColor='#6d94b5';
Generating random numbers
constnum=game.rnd.integerInRange(120,480);constintNum=game.rnd.integer();constfracNum=game.rnd.frac();//Spawn a sprite at a random positiongame.add.sprite(game.world.randomX,game.world.randomY,'mysprite');
Adding game objects
functioncreate(){//image, sprite, audio and others are all methods of the factorygame.add.image(x,y,'key');varplayer=game.add.sprite(x,y,'key',frame,group);//You can add existing objects toovarsprite=newPhaser.Sprite(game,x,y,'key');game.add.existing(sprite);}
Repositioning an objects anchor
//Objects have an anchor property that goes from 0 (top left) to 1 (bottom right)//It defaults to 0,0 but it can be changed easilyimage.anchor.x=0.2;image.anchor.y=1;//This sets it in the middleimage.anchor.setTo(0.5,0.5);
Scaling an object
//Objects have a scale property that defaults to 1//Negative values essentially mirror it on the affected axisimage.scale.x=-1;//This doubles the size of the objectimage.scale.setTo(2,2);
Displaying an image
functioncreate(){game.add.image(x,y,'key');}
Working with sprites
functioncreate(){//Assign it to a variable so we can reference itconstsprite=game.add.sprite(x,y,'key');//Now we can access its properties and methodssprite.x=200;sprite.y=300;}
functioncreate(){//Assign it so we can reference it laterconstrun=sprite.animations.add('name',[frames],frameRate,loop);//Second parameter is the context, usually 'this'run.onStart.add(listener,this);}functionlistener(){console.log("You just started running!");}
Displaying text
functioncreate(){//Assigned for later useconstlabel=game.add.text(x,y,"text",{style},group);label.text="I'm changing the text inside the label var!";//Center the textconsttxt=game.add.text(game.world.centerX,game.world.centerY,"My Text");txt.anchor.set(0.5,0.5);}
Tweening
//Adding an example sprite but you can tween pretty much anythingconstplayer=game.add.sprite(100,100,'player');game.add.tween(player).to({x:500},400)//change player.x to 500 over 400ms.start();
Playing music
functioncreate(){//Assign it so we can reference it varmusic=game.add.audio('key',volume,loop);music.loop=true;music.play();}
Working with timers
//Three types of timers: looping, one time event, repeat.constlooping=game.time.events.loop(delay,callback,context);constonce=game.time.events.add(delay,callback,context);constrepeat=game.time.events.repeat(delay,repeatCount,callback,context);//You can also pass one last argument with the callback argumentsgame.time.events.pause(loopingTimer);game.time.events.remove(once);
Calculating elapsed time
//You can get the current timeconstcurrentTime=game.time.time;//You can get the elapsed time (milliseconds) since the last updateconstelapsedTime=game.time.elapsed;//Or you can get the elapsed time (seconds) since the last event trackedconstlastEventTrackedTime=game.time.time;//Do something...constelapsedTime=game.time.elapsedSecondsSince(lastEventTrackedTime);
Input
//Input can come from mouse, touch or keyboard//This is the parent object, with properties for setting how input works//Allows up to a second between taps for a double clickgame.input.doubleTapRate=1000;//Increases the hitbox for touchgame.input.circle=66;
Mouse & touch input
if(game.input.mousePointer.isDown){console.log("Mouse X when you clicked was: "+game.input.mousePointer.x);}//Assign a callback and a context to a click eventgame.input.onDown.add(callback,context);
Keyboard input
if(game.input.keyboard.justReleased(Phaser.Keyboard.SPACEBAR,10000)){console.log("Spacebar has been pressed in the last 10 seconds.");}//Assigning Up, Down, Left and Right to a variableconstarrow=game.input.keyboard.createCursorKeys();if(arrow.up.isDown){console.log("You are pressing the up arrow!");}//This will stop the arrow keys from scrolling the pagegame.input.keyboard.addKeyCapture(arrow);
Working with groups
//Remember to assign it so we can reference itconstenemies=game.add.group();//We can add an already created objectenemies.add(button);//Or we can create a new object in the groupenemies.create(x,y,'enemy_sprite');//You can use setAll to modify properties across all childrenenemies.setAll('x',500);
Adding physics to Sprites
functioncreate(){//First we start the systemgame.physics.startSystem(Phaser.Physics.ARCADE);//We then create our sprite & enable physics on itsprite=game.add.sprite(x,y,'key');game.physics.enable(sprite,Phaser.Physics.ARCADE);//Now our sprite has an object body as a propertysprite.body.velocity.setTo(x,y);sprite.body.bounce.set(0.8);}
Handling Collision
functionupdate(){//You can collide a group with itselfgame.physics.arcade.collide(sprites);//You can call a function when a collision happensgame.physics.arcade.collide(sprites,monsters,callback);//You can perform additional checks with a processCallback//If it returns false the collision will not happengame.physics.arcade.collide(sprites,monsters,null,processCallback);//Or you can check if two bodies overlap. This method avoids the impact//between then, keeping their velocities and propertiesgame.physics.arcade.overlap(sprites,monsters,callback);//You can perform the following collisions://Sprite vs Sprite or//Sprite vs Group or//Group vs Group or//Sprite vs Tilemap Layer or//Group vs Tilemap Layer}
Camera
//Lets follow a sprite named 'missile'game.camera.follow(missile);//Once the missile explodes, maybe we want to reset the cameragame.camera.reset();//Something cool is happening, let's pan the camera theregame.camera.x=500;
Particles
emitter=game.add.emitter(x,y,maxParticles);emitter.makeParticles('image');emitter.setAlpha(min,max,rate,easing,yoyo);//To use gravity on the emitter, start the physics systemgame.physics.startSystem(Phaser.Physics.ARCADE);emitter.gravity=200;emitter.start();
Debugging
//Print debug textgame.debug.text(game.time.physicsElapsed,10,20);//Print debug body informationgame.debug.bodyInfo(player,10,20);//Show the sprite's hitbox as a green rectanglegame.debug.body(player);