Lunar Lander
In this game you will use the arrow keys to navigate the Lunar Lander spacecraft to a soft landing on the Landing Pad.
Setup our Index Page
Create a new Plunk. Edit the index.html file to look like below. The Index file is what loads our Phaser Game Engine and our javascript game file.
<html>
<head>
<script src="//cdn.jsdelivr.net/phaser/2.6.2/phaser.min.js"></script>
<script src="game.js"></script>
</head>
<body>
<div id="gameBoard"></div>
</body>
</html>
Create our Javascript Game file
Create a new file called game.js and copy the code below into it.
This game will have 2 states. One state is for our games Main Menu.
The other state is for our games first level.
// Game: LunarLander
// GAME STATE - MAIN MENU
// -----------------------------------------------------------------
var MainMenuState = {
preload: function() {
},
create: function() {
},
update: function() {
},
loadCompleted: function() {
this.create;
}
};
// GAME STATE - LEVEL 1
// -----------------------------------------------------------------
var Level1State = {
// This is a property of the Level1State.
// If it is set to true, the game is over. We set it to false initially.
ThisLevelIsOverDude: false,
preload: function() {
// nothing here because we now load all image data in our main-menu-state6
},
create: function() {
},
update: function() {
},
gameOver: function() {
// display game over and instructions
game.add.text(50,100,'GAME OVER \n Restart? \n press spacebar', {font: '40px Arial', fill: '#ffffff' });
// this level is over
Level1State.ThisLevelIsOverDude = true;
}
};
// GAME - INITIALIZE
// -----------------------------------------------------------------
// Startup the Phaser Game Engine
var game = new Phaser.Game(600, 500, Phaser.AUTO, 'gameBoard');
// add game scenes ( game states ) to the phase game engine
game.state.add('mainmenu', MainMenuState);
game.state.add('level1', Level1State);
// Start Game!
game.state.start('mainmenu');
Run Your Code and check for errors.
You should get a nice black canvas. Press F12 to open the Developer Tools, click Console tab and make sure there are no errors.
Create the Games Main Menu
Add this code to replace the CREATE and UPDATE function of the MainMenuState.
This code will display our games main menu.
create: function() {
// display a main menu and instructions
game.add.text(50, 80, 'LUNAR LANDER',
{
font: '50px Arial',
fill: '#ffffff'
});
game.add.text(50, 200, 'Main Menu \n> press spacebar to start!',
{
font: '25px Arial',
fill: '#00ff2e'
});
// need a keyboard object to capture users input
this.keyboard = game.input.keyboard;
},
update: function() {
// check if user is pressing spacebar
if (this.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) {
// start level
game.state.start('level1');
}
},
Run Your Code and check for errors.
You should see the games main menu. Press spacebar to start up our Level1State which will just show a black screen for now.
Load in our Games Image Data
Replace the PRELOAD function of the MainMenuState with the code below.
This code will load in all our image data needed for our sprites.
notice we have four images of our rocket. each one is a little different to show fire coming out of the engines.
preload: function() {
// load in all our image data we will use during our game
// image data for ROCKET
// -------------------------------------------------------------------------
var rocketEngineOffData = [
'..2222..',
'.292292.',
'.292292.',
'.222222.',
'..2222..',
'..2222..',
'.22..22.',
'.2....2.'
];
game.create.texture('rocketEngineOff', rocketEngineOffData, 3, 3, 0);
var rocketEngineDownOnData = [
'..2222..',
'.292292.',
'.292292.',
'.222222.',
'..2222..',
'..2222..',
'.223322.',
'.2.33.2.'
];
game.create.texture('rocketEngineDownOn', rocketEngineDownOnData, 3, 3, 0);
var rocketEngineLeftOnData = [
'..2222..',
'3292292.',
'.292292.',
'.222222.',
'..2222..',
'..2222..',
'.22..22.',
'.2....2.'
];
game.create.texture('rocketEngineLeftOn', rocketEngineLeftOnData, 3, 3, 0);
var rocketEngineRightOnData = [
'..2222..',
'.2922923',
'.292292.',
'.222222.',
'..2222..',
'..2222..',
'.22..22.',
'.2....2.'
];
game.create.texture('rocketEngineRightOn', rocketEngineRightOnData, 3, 3, 0);
// image data for GROUND
// -------------------------------------------------------------------------
var groundData = [
'55555555',
'56565656',
'65656565',
'56565656'
];
game.create.texture('ground', groundData, 3, 3, 0);
// image data for LANDING PAD
// -------------------------------------------------------------------------
var pad_aData = [
'BBBBBBBB',
'99999999',
'9.9..9.9',
'9.9..9.9'
];
game.create.texture('pad_a', pad_aData, 3, 3, 0);
// the computer will take a few seconds to upload our image data into the game engine.
// when the load is complete
game.load.onLoadComplete.add(this.loadCompleted, this);
game.load.start();
},
Run Your Code and check for errors.
You should see the games main menu. Press spacebar to start up our Level1State which will just show a black screen for now. Our game image data should be ready to use now.
Level 1 Game State
Add this code to the CREATE function of the Level1State.
This code will setup our game environment for the first level of our game.
If you want to change your games background, google 'rgb color picker'.
Use the tool to choose your color then copy and paste the RGB code (the number that looks like this "#3298d3").
// create all our game objects and setup our game environment
//---------------------------------------------------------------
// add physics to this level
game.physics.startSystem(Phaser.Physics.ARCADE);
// change background color
game.stage.backgroundColor = "#000000";
// need a keyboard object to capture users input
this.keyboard = game.input.keyboard;
Run Your Code and check for errors.
Your games background should now be the color you choose.
Create our Rocket
Add this code to the CREATE function of the Level1State.
This code will create our rocket object.
// create rocket object
// ------------------------------------------------------------
// create the rocket object and add physics property to it
this.rocket = game.add.sprite(10, 10, 'rocketEngineOff');
game.physics.enable(this.rocket, Phaser.Physics.ARCADE);
// Set the pivot point to the center of the sprite object
this.rocket.anchor.setTo(0.5, 0.5);
Run Your Code and check for errors.
You should see the rocket on the screen now.
Put our Rocket in Motion
Add this code to the CREATE function of the Level1State.
This code will put our rocket in motion by adding some velocity to it.
// put the rocket in motion
this.rocket.body.velocity.x = 10;
Run Your Code and check for errors.
You should see the rocket move across the screen.
Add Gravity to our Rocket
Add this code to the CREATE function of the Level1State.
This code will add gravity to our rocket so it gets pulled toward the moon (or bottom of screen).
// set rockets gravity effect on the Y-Axis (up-down axis)
this.rocket.body.gravity.y = 100;
Run Your Code and check for errors.
You should see the rocket get pulled to the bottom of the screen.
Move our Rocket using Arrow Keys
Add this code to the UPDATE function of the Level1State.
This code will allow us to move our rocket around using the arrow keys.
Notice that everytime we fire an engine, we change the rocket image to one with the appropriate red engine thrust showing.
// logic to move rocket using it's three engines
// --------------------------------------------------------------------
// rocket engines are off
var RocketEngineOff = true;
// check if user is pressing the UP arrow, which means we need to fire the bottom engine on the rocket
if (this.keyboard.isDown(Phaser.Keyboard.UP)) {
// up arrow is being pressed, so show image with down thruster on
this.rocket.loadTexture('rocketEngineDownOn', 0);
// increase current velocity by 10
this.rocket.body.velocity.y += -5;
// rocket engine is on
RocketEngineOff = false;
}
// check if user is press the left arrow
if (this.keyboard.isDown(Phaser.Keyboard.LEFT)) {
// left arrow is being pressed, so show image with left thruster on
this.rocket.loadTexture('rocketEngineRightOn', 0);
// increase velocity
this.rocket.body.velocity.x += -3;
// rocket engine is on
RocketEngineOff = false;
}
// check if user is press the right arrow
if (this.keyboard.isDown(Phaser.Keyboard.RIGHT)) {
// left arrow is being pressed, so show image with left thruster on
this.rocket.loadTexture('rocketEngineLeftOn', 0);
// increase velocity
this.rocket.body.velocity.x += 3;
// rocket engine is on
RocketEngineOff = false;
}
// if user is not pressing anything, then show image with no engines on.
if (RocketEngineOff === true) {
this.rocket.loadTexture('rocketEngineOff', 0);
}
Run Your Code and check for errors.
You should be able to move the rocket around and see it's thrusters fire
Create a Landing Pad
Add this code to the CREATE function of the Level1State.
This code will add our landing pad sprite to the game.
// create a landing pad
// ------------------------------------------------------------
// create the landing pad object and add physics property to it
this.pad_a = game.add.sprite(550, 450, 'pad_a');
game.physics.enable(this.pad_a, Phaser.Physics.ARCADE);
// set the pivot point to the center of the sprite object
this.pad_a.anchor.setTo(0.5, 0.5);
// make this object immovable
this.pad_a.body.immovable = true;
Run Your Code and check for errors.
You should see a landing pad in the game. Try landing the rocket on the landing pad. Next, we will add code to check if the rocket touches the pad.
Check if Rocket Touches Pad
This code will check if the rocket has landed on the pad.
Step 1: add this new function called 'touchDown' after the update function and before the gameOver function in the Level1State. This function is executed when a collision between the pad and rocket is detected by the phaser game engine.
touchDown: function(_rocket, _pad_a) {
// stop all rocket motion
_rocket.body.enable = false;
// display game over and instructions
game.add.text(50,20,'TOUCH DOWN!!', {font: '50px Arial', fill: '#02f20e' });
// display game over and instructions
game.add.text(50,100,'Restart? \npress spacebar', {font: '40px Arial', fill: '#ffffff' });
// this level is over
Level1State.ThisLevelIsOverDude = true;
},
Step 2: add this code to the end of the update function in the Level1State. This code tells the Phaser Game engine to look out for a collision between the rocket and the pad. If there is a collision the touchDown function above will be called.
// check if rockets lands on pad
// --------------------------------------------------------------------
game.physics.arcade.overlap(this.rocket, this.pad_a, this.touchDown);
Run Your Code and check for errors.
Try landing on the pad now! Next, lets add code to restart the game if we land.
Restart Game
Add this code to the end of the UPDATE function of the Level1State.
This code will restart the game if the game is over.
// check if this level is over
// --------------------------------------------------------------------
if (Level1State.ThisLevelIsOverDude === true) {
// check if user is pressing spacebar
if (this.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) {
Level1State.ThisLevelIsOverDude = false;
game.state.start('mainmenu');
}
}
Run Your Code and check for errors.
Try landing again. The game should allow you to restart, taking you back to the main menu.
Check if Rocket goes out of bounds
Add this code to the CREATE function of the Level1State.
This code will check if the rocket goes out of bounds (or off the screen).
// check if rocket leaves the game
this.rocket.checkWorldBounds = true;
// if rocket leaves the game (is out of bounds), call the 'gameOver' function
this.rocket.events.onOutOfBounds.add(this.gameOver, this);
Run Your Code and check for errors.
Let the rocket go off the screen. You should see the Game Over screen now.
You're done! You are a coder!
What other things can you add to this game?
What other games can you make up using this code!?
MORE! Add some ground objects
The code below will add a group of blocks. You can put the blocks anywhere you like.
Add this code to the CREATE function of the Level1State. This code will create our group object which will hold all our blocks.
// create a group of block objects
this.blocks = game.add.group();
Add this function between the CREATE and UPDATE function of the Level1State. This code will create a block and add it to our group of blocks object.
makeBlock: function(x,y) {
// this function will create a new block object at position X and Y
// and add it to the "group of blocks" object we created
// create our first block object (make a block look like the ground)
this.block = game.add.sprite(x,y, 'ground');
// enable physics on our block
game.physics.enable(this.block, Phaser.Physics.ARCADE);
// nothing can move this sprite
this.block.body.immovable = true;
// set the blocks anchor to the center of the block
this.block.anchor.setTo(0.5, 0.5);
// add block to our group of blocks.
this.blocks.add(this.block);
},
Add this code to the CREATE function of the Level1State. This code will call our new makeBlock function with a different X and Y position, creating a new block every time. You can add as many as you want, anywhere.
this.makeBlock(450,400);
this.makeBlock(475,400);
this.makeBlock(500,400);
Add this code to the end of UPDATE function of the Level1State. This code will check if the rocket touches the ground and execute the Game Over function.
// check if rockets hits the ground
// --------------------------------------------------------------------
game.physics.arcade.overlap(this.rocket, this.blocks, this.hitGround);
Add this function before the gameOver function of the Level1State. This function is executed when the game engine detects the rocket hitting any ground object.
hitGround: function(_rocket) {
// stop all rocket motion
_rocket.body.enable = false;
// display game over and instructions
game.add.text(50,100,'EXPLOSION! GAME OVER \n Restart? \n press spacebar', {font: '40px Arial', fill: '#ffffff' });
// this level is over
Level1State.ThisLevelIsOverDude = true;
},
Run Your Code and check for errors.
Avoid the ground this time!
code on plnkr