Bobber

In this game you need to help Bob get across the road without getting run over by a truck. Use arrow keys to move Bob around.



Basic Game Template
First, create a new file called 'game.js', then add the code below which is the basic framework for our game. We will then fill in the PRELOAD, CREATE and UPDATE functions. Make sure you also update your HTML file with links to your game and phaser engine. If you need help see the tutorial 'basic game template'.



                 
// GAME: bobber


var level1state = { 


  // the preload function allows us to load in all the data we need for our game
  preload: function() {

    
  },


  // the create function is where we create all our game objects
  create: function() {


  },
  
  
  
  // the update function runs continously during our game
  update: function() { 


  },

 
  // game over function
  gameOver: function() { 

    // make bob invisible
    this.bob.visible = false;
  
    // display instructions to restart game
    var Title = game.add.text(50,80,'Play Again? \n (press spacebar)', {font: '50px Arial', fill: '#ffffff' });

    // check if SPACEBAR key pressed
    var spacebar = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
    spacebar.onDown.addOnce(this.start, this);
  
  },
  
  // starts the game
  start: function(){
    level1state.ThisLevelIsOverDude = false;
    game.state.start('level1');
  }
  

}; 
  

// 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('level1', level1state);

// Start Game 
game.state.start('level1');

              
            
        

Run Your Code and check for errors.
You should get a nice black canvas





Load Data for Sprites
Add this code to the PRELOAD function. This will load all the data we need for our sprite images.


              
   // load in data for our game images

    var bobRaw = [
      '...666...',
      '..6E.E6..',
      '..2...2..',
      '...222...',
      '....4....',
      '..84448..',
      '...777...',
      '...7.7...'
    ];
    game.create.texture('bob', bobRaw, 6, 6, 0);

    var truckRaw = [
      '........',
      '.6666...',
      '.6556...',
      '26556666',
      '66665666',
      '66666666',
      '.00..00.',
      '.00..00.'
    ];
    game.create.texture('truck', truckRaw, 6, 6, 0);

                
        

Run Your Code and check for errors.
Press F12 to check console tab for any errors. Next we will create our game objects.





Setup our Game Environment
Add this code to the CREATE function. This will add Physics to our game and create a keyboard game object which we can use to get user input.



    // add physics to this level    
    game.physics.startSystem(Phaser.Physics.ARCADE);

    // need a keyboard object to capture users input
    this.keyboard = game.input.keyboard;

            
        



Create Bob!
Add this code to the CREATE function. This will create our game object called BOB using the image data we loaded in the preload.



    // create bob object
    this.bob = game.add.sprite(200, 450, 'bob');
    game.physics.enable(this.bob, Phaser.Physics.ARCADE);

    // Set the pivot point to the center of the sprite object
    this.bob.anchor.setTo(0.5, 0.5);
                
            
        




Run Your Code and check for errors.
You should see BOB on the screen now. remember you might have to run it twice to see bob show up.


Make Bob Move
Add this code to the UPDATE function. This captures input from our keyboard object and changes Bob's velocity.



    // Check if user is pressing arrow keys and change Bobs velocity
    if (this.keyboard.isDown(Phaser.Keyboard.LEFT)) {
      this.bob.body.velocity.x = -250;
    }
    if (this.keyboard.isDown(Phaser.Keyboard.RIGHT)) {
      this.bob.body.velocity.x = 250;
    }
    if (this.keyboard.isDown(Phaser.Keyboard.UP)) {
      this.bob.body.velocity.y = -250;
    }
    if (this.keyboard.isDown(Phaser.Keyboard.DOWN)) {
      this.bob.body.velocity.y = 250;
    }
            
        

Run Your Code and check for errors.
Use the arrow keys to make Bob move around.





Make Bob Stop Moving
Did you notice Bob doesn't stop moving. Let's set his velocity to 0 before we check if the user is pressing the arrow keys. If they don't press any arrow keys, Bob's velocity will stay at zero.
Your code that moves Bob should now look like below.



    // set bobs velocity to zero
    this.bob.body.velocity.x = 0;
    this.bob.body.velocity.y = 0;

    // Check if user is pressing arrow keys and change Bobs velocity
    if (this.keyboard.isDown(Phaser.Keyboard.LEFT)) {
      this.bob.body.velocity.x = -250;
    }
    if (this.keyboard.isDown(Phaser.Keyboard.RIGHT)) {
      this.bob.body.velocity.x = 250;
    }
    if (this.keyboard.isDown(Phaser.Keyboard.UP)) {
      this.bob.body.velocity.y = -250;
    }
    if (this.keyboard.isDown(Phaser.Keyboard.DOWN)) {
      this.bob.body.velocity.y = 250;
    }
            
        

Run Your Code and check for errors.
Use the arrow keys to make Bob move around. He should stop moving now when u release the arrow key.





Create our Truck Objects
Add this code to the CREATE function. This code will create a group object. A group object will allow us to store several truck objects we create. We are going to create five truck objects. When we need a truck object, we can just take one from our collection of truck objects stored in our group.



    this.NUMBER_OF_TRUCKS = 5;

    // create a pool or collection or group of trucks
    this.trucks = this.game.add.group();
    for (var j = 0; j < this.NUMBER_OF_TRUCKS; j++) {

      // Create a truck and add it to the group.
      var truck = this.game.add.sprite(0, 0, 'truck');
      this.trucks.add(truck);

      // Set its pivot point to the center of the sprite
      truck.anchor.setTo(0.5, 0.5);

      // Enable physics on the sprite object
      this.game.physics.enable(truck, Phaser.Physics.ARCADE);

      // Set its initial state to "dead".
      truck.kill();
    }
            
        



Add a function to create a truck
Add this new function after the UPDATE function.



    createAtruck: function() {

    // get a dead truck from the pool of trucks
    var truck = this.trucks.getFirstDead();

    // if there are no trucks available, then don't do anything
    if (truck === null || truck === undefined) return;

    // revive a truck
    truck.revive();

    // kill truck if he leaves world
    truck.checkWorldBounds = true;
    truck.outOfBoundsKill = true;

    // !! set the position where the truck will appear !!
    // get a random number between 1 and 2
    var randomNumber = game.rnd.integerInRange(1,2);
    if (randomNumber == 1) { 
      truck.reset(550, 250);
    }
    if (randomNumber == 2) {
      truck.reset(550, 150);
    }

    // make truck move across the screen at a fixed velocity
    truck.body.velocity.y = 0;
    truck.body.velocity.x = -200;

  },

            
        



Add some trucks to our game
Add this line of code to the UPDATE function.



        this.createAtruck();
            
        

Run Your Code and check for errors.
You should see a couple of trucks move across the screen.





Release Truck Timer
Now that we have trucks in our game, we need to control when they are released instead of releasing a truck every frame of our game. Let's modify the previous line of code and add an IF statement which only releases a truck at random intervals of our game clock.
Change your 'createATruck' line of code in your UPDATE function to below.



    // create a truck when it's time...using our 'releaseTruckTime' variable
    var currentTime = this.game.time.totalElapsedSeconds(); 
    if (this.game.time.totalElapsedSeconds() > this.releaseTruckTime) {
      
      this.releaseTruckTime =  currentTime + game.rnd.integerInRange(.5,1);
      
      this.createAtruck();
    }
            
        

Add this line of code to the CREATE function. This will set our releaseTruckTime to 1 to start it off.



        // time to release another truck
        this.releaseTruckTime = 1;
        
        

Run Your Code and check for errors.
You should see several trucks moving across the screen now at different times. Move Bob around and see what if anything happens when he runs into a truck.





Check if Bob gets hit by a truck
Add this line of code to the beginning of our UPDATE function. This code will check if bob overlaps with any of our trucks in our truck group. If there is an overlap, the deadBob function will be called.



    // did bob hit a truck?
    game.physics.arcade.overlap(this.bob, this.trucks, this.deadBob, null, this);
            
        




End the game when Bob gets hit
Add this function before the gameOver function.



deadBob: function(bob, truck) {
    bob.kill();
    truck.kill();
    this.gameOver();
  },
            
        

Run Your Code and check for errors.
Move bob over a truck. The game should stop.







code on plnkr