Book Image

Learning Cocos2d-JS Game Development

By : Emanuele Feronato
Book Image

Learning Cocos2d-JS Game Development

By: Emanuele Feronato

Overview of this book

Table of Contents (18 chapters)
Learning Cocos2d-JS Game Development
Credits
Foreword
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
9
Creating Your Own Blockbuster Game – A Complete Match 3 Game
Index

Adding the spaceship


The spaceship you are going to add is just another sprite, but you are going to give it behavior like it was ruled by gravity.

First, let' s add a couple of variables:

var background;
var gameLayer;
var scrollSpeed = 1;
var ship;
var gameGravity = -0.05;

The ship variable will be the spaceship itself, whereas gameGravity is the force that will attract the spaceship toward the bottom of the screen.

Then, inside the init function in game declaration, you add the ship in the same way you added the background:

var game = cc.Layer.extend({
  init:function () {
    this._super();
    background = new ScrollingBG();
    this.addChild(background);
    this.scheduleUpdate();
    ship = new Ship();
    this.addChild(ship);
  },
  update:function(dt){
    background.scroll();
    ship.updateY();
  }
});

Then, in the update function (remember this function is automatically called at each frame). Thanks to the scheduleUpdate method, an updateY custom method is called.

The creation of the...