rapid game development using cocos2d-jssamples.leanpub.com/cocos2d-sample.pdf · getting started...

14

Upload: others

Post on 12-Sep-2019

13 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Rapid Game Development Using Cocos2D-JSsamples.leanpub.com/cocos2d-sample.pdf · Getting Started Introduction Intheearlydays,gamesarehardertomake,butintherecentyearslotsof2D,3Dframeworksand
Page 2: Rapid Game Development Using Cocos2D-JSsamples.leanpub.com/cocos2d-sample.pdf · Getting Started Introduction Intheearlydays,gamesarehardertomake,butintherecentyearslotsof2D,3Dframeworksand

Rapid Game Development Using Cocos2D-JSAn End-To-End Guide to 2D Game Development usingJavascript

Hemanthkumar and Abdul Rahman

This book is for sale at http://leanpub.com/cocos2d

This version was published on 2015-11-02

This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishingprocess. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools andmany iterations to get reader feedback, pivot until you have the right book and build traction onceyou do.

©2015 Nutcrackify

Page 3: Rapid Game Development Using Cocos2D-JSsamples.leanpub.com/cocos2d-sample.pdf · Getting Started Introduction Intheearlydays,gamesarehardertomake,butintherecentyearslotsof2D,3Dframeworksand

Also By Hemanthkumar and Abdul RahmanAdvanced Javascript in 60 minutes

Page 4: Rapid Game Development Using Cocos2D-JSsamples.leanpub.com/cocos2d-sample.pdf · Getting Started Introduction Intheearlydays,gamesarehardertomake,butintherecentyearslotsof2D,3Dframeworksand

Contents

Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Environment Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Creating your first app . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Running the sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

Architecture Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Engine Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8JSB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Object Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Deploy Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

Page 5: Rapid Game Development Using Cocos2D-JSsamples.leanpub.com/cocos2d-sample.pdf · Getting Started Introduction Intheearlydays,gamesarehardertomake,butintherecentyearslotsof2D,3Dframeworksand

Getting StartedIntroduction

In the early days, games are harder to make, but in the recent years lots of 2D,3D frameworks andtools are evolved which simplify’s the game development and enable developers to produce the highquality games quickly. Cocos is one among those which is widely used game engine for making 2Dgames, Over the years Cocos has established the solid foundation among developers. Many populargames in the market are made using Cocos.Later in 2010 Cocos2d-x which is C++ port of Cocos2Dwas introduced which enabled developers to make cross platform 2D games.After that Cocos2d-jswhich is javascript port of Cocos2d was introduced, which enables developers to produce browserbased games also cross platform native games which uses JSB.

Cocos2D is the proven standard for making 2D games due to its simplicity and rich sets of features.In the coming sections we going to have deep look at Cocos2d-js framework and its features. By endof this book you will have solid understanding of Cocos2D-js framework, best practices rich sets offeatures which enable you to develop your awesome game quickly.

Let’s Begin !

Environment Setup

Python Installation

Most of the time you will be dealing with cocos console to create, run , compile and deploy youproject which uses python. So First thing you need to install python. you can download it from theofficial python site.

https://www.python.org/downloads/

Android Setup

You can skip this part if you already have android environment or you don’t want to compile anddeploy for android.

Steps

• Install JDK from http://www.oracle.com/technetwork/java/javase/downloads/index.html

Page 6: Rapid Game Development Using Cocos2D-JSsamples.leanpub.com/cocos2d-sample.pdf · Getting Started Introduction Intheearlydays,gamesarehardertomake,butintherecentyearslotsof2D,3Dframeworksand

Getting Started 2

• Download android studio or SDK andNDK fromhttps://developer.android.com/sdk/index.html• Extract the SDK if you are not installing the android studio.• Extract the NDK and place it in the root of SDK, make sure that SDK and NDK are in sameroot folder.

• Install Apache ant https://ant.apache.org/bindownload.cgi

iOS Setup

• By default all the Mac got iOS setup preinstalled. So there are no specific steps.

Window Phone Setup

• Download and install Visual Studio 2015, if you are independent developer VS communityedition is available which is free of cost.

• By default VS2015 has Window Phone SDK installer which will install as part of VSinstallation.

Cocos2d-x Setup

For Cocos2d-js is environment is actually part of Cocos2d-x, so you have to download the cocos2d-xbundle.

Sample For This Book

All the sample code for this book is available at

https://github.com/nutcrackify/Rapid_Game_Development_Using_Cocos2d-js

Clone this repository in your local and follow the provided instructions to run it.

Steps

• Download the cocos2d-x bundle from https://cocos2d-x.org/download• Extract the zip in your local.• Open the terminal on Mac or Command Prompt on Windows and navigate to the extractedfolder.

• Run the below command python setup.py• This will setup the cocos console which uses android,ios,window phone environment settingsand update the environment variables.

Page 7: Rapid Game Development Using Cocos2D-JSsamples.leanpub.com/cocos2d-sample.pdf · Getting Started Introduction Intheearlydays,gamesarehardertomake,butintherecentyearslotsof2D,3Dframeworksand

Getting Started 3

Creating your first app

Create a separate folder of your choice in your favorite location. It is good practices to keep you allcocos2d-js projects under one root folder.

Open terminal and navigate to the created folder path, execute the below command

1 cocos new sampleproject -l js

where sampleproject is the name of your project and -l js specifies the language javascript. Thiscreates the hello world sample, you can use this project as base for your game. For our understandingwe going to modify this app to make our own hello world screen.Before that you should understandthe folder structure which cocos2d-js follows.

Folder Structure

When you create a new project cocos console will create a folder structure like below.

Project folder structure

src folder is where you have all the javascript files for your game, res folder is where you have all theimage and other resources which is referenced in your game frameworks folder is where you haveactual cocos2d-js engine, support files for native deployment, JSB so on. apart from this there areconfiguration files project.json which serves as main configuration for the runtime for your gameand mainfest.webapp which has configuration related to web.

Code

If you open main.js you will see the below code.

Page 8: Rapid Game Development Using Cocos2D-JSsamples.leanpub.com/cocos2d-sample.pdf · Getting Started Introduction Intheearlydays,gamesarehardertomake,butintherecentyearslotsof2D,3Dframeworksand

Getting Started 4

1 cc.game.onStart = function(){

2 //If referenced loading.js, please remove it

3 if(!cc.sys.isNative && document.getElementById("cocosLoading"))

4

5 document.body.removeChild(document.getElementById("cocosLoading"));

6

7 // Pass true to enable retina display, disabled by default to improve perfor\

8 mance

9 cc.view.enableRetina(false);

10 // Adjust viewport meta

11 cc.view.adjustViewPort(true);

12 // Setup the resolution policy and design resolution size

13 cc.view.setDesignResolutionSize(800, 450, cc.ResolutionPolicy.SHOW_ALL);

14 // The game will be resized when browser size change

15 cc.view.resizeWithBrowserSize(true);

16 //load resources

17 cc.LoaderScene.preload(g_resources, function () {

18 cc.director.runScene(new HelloWorldScene());

19 }, this);

20 };

21 cc.game.run();

At first, the cocos2d-js engine will begin by executing onStart function which has code to kick startyour game there are few configuration related things going on in the above code which will beexplained in later chapters. For now will focus on cc.LoaderScene part.

1 cc.LoaderScene.preload(g_resources, function () {

2 cc.director.runScene(new HelloWorldScene());

3 }, this);

The above code loads the hello world scene, cc.director is the signle-ton controller instance for yourgame. purpose of this director is to guide your game through the execution,load and unload thescene getting info about the game execution environment such as screen size and so on. In thiscode director use runScene function to load the HelloWorldScene, the scene is loaded inside preloadbeacuse. preload loads the resources specified in g_resources into cocos cache, once resource hasbeen loaded callback function is executed which has code to load the HelloWorldScene.

Let’s have look at HelloWorldScene and HelloWorldLayer.Open app.js inside src, in the bottom ofapp.js you will see a code like this

Page 9: Rapid Game Development Using Cocos2D-JSsamples.leanpub.com/cocos2d-sample.pdf · Getting Started Introduction Intheearlydays,gamesarehardertomake,butintherecentyearslotsof2D,3Dframeworksand

Getting Started 5

1 var HelloWorldScene = cc.Scene.extend({

2 onEnter:function () {

3 this._super();

4 var layer = new HelloWorldLayer();

5 this.addChild(layer);

6 }

7 });

A scene is begin to run by invoking onEnter function, in that HellowWorldLayer is injected as childfor scene.

We going to modify HelloWorldLayer to make things simple.

1 var HelloWorldLayer = cc.Layer.extend({

2 sprite:null,

3 ctor:function () {

4 this._super();

5 var size = cc.winSize;

6 var helloLabel = new cc.LabelTTF("Hello World", "Arial", 38);

7 // position the label on the center of the screen

8 helloLabel.x = size.width / 2;

9 helloLabel.y = size.height / 2 + 200;

10 // add the label as a child to this layer

11 this.addChild(helloLabel, 5);

12

13 // add "HelloWorld" splash screen"

14 this.sprite = new cc.Sprite(res.HelloWorld_png);

15 this.sprite.attr({

16 x: size.width / 2,

17 y: size.height / 2

18 });

19 this.addChild(this.sprite, 0);

20 return true;

21 }

22 });

This layer has two child, one is cc.LabelTTF which has hello world as text and a hello world pngsprite. Throught this bookwe going to use portrait screen resolution. So inmain.js you should changethe below line

Page 10: Rapid Game Development Using Cocos2D-JSsamples.leanpub.com/cocos2d-sample.pdf · Getting Started Introduction Intheearlydays,gamesarehardertomake,butintherecentyearslotsof2D,3Dframeworksand

Getting Started 6

1 //This is landscape

2 cc.view.setDesignResolutionSize(800, 450, cc.ResolutionPolicy.SHOW_ALL);

To

1 //Swap the width and height so that is can be portrait

2 cc.view.setDesignResolutionSize(450, 800, cc.ResolutionPolicy.SHOW_ALL);

Width and Height has been swapped.

Running the sample

To make things simple, Through this book we going to run all the code in web browser, on the otherhand deploying it in device as native app is your choice. To run this sample type the navigate to theproject path in terminal and type below command

1 cocos run -p web

This will launch the app in browser, however you can launch the app in android, ios , window phoneby altering -p param as ‘android’, ‘ios’,’wp_81’ You will see something like below

Page 11: Rapid Game Development Using Cocos2D-JSsamples.leanpub.com/cocos2d-sample.pdf · Getting Started Introduction Intheearlydays,gamesarehardertomake,butintherecentyearslotsof2D,3Dframeworksand

Getting Started 7

Hello World

In the next chapter we going to look at engine architecture, so let roll on.

Page 12: Rapid Game Development Using Cocos2D-JSsamples.leanpub.com/cocos2d-sample.pdf · Getting Started Introduction Intheearlydays,gamesarehardertomake,butintherecentyearslotsof2D,3Dframeworksand

Architecture OverviewEngine Architecture

Understanding the architecture of cocos2d-js will give you a solid foundation about the framework.This section will not cover the detailed architecture which is beyond the scope of this book Howeverwe will cover the necessary details that you need to be aware of in order to move forward. Cocos2d-js is pure javascript based game framework which runs on browser stack, you can compile it as webapp and run in on every browser, however the api’s and object’s hierarchy are same as of Cocos2d-x.So with the help of JSB and spidermonkey, your javascript game code can be deployed as native appwhich actually utilize the core rendering pipeline of OpenGL/DirectX. Let’s see have a look at thearchitecture.

Cocos2d-js Stack

As you see, if your app is browser based, your javascript game code will utilize cocos2d-js libraryand can be run like any other web app. When you deploy this as native app using cocos console, yourjavascript code will be mapped to javascript bindings which actually points to native cocos2d-x. Andyour javascript code will be converted to C by spidermonkey. So cocos2d-x will actually drive yourjavascript game.

Page 13: Rapid Game Development Using Cocos2D-JSsamples.leanpub.com/cocos2d-sample.pdf · Getting Started Introduction Intheearlydays,gamesarehardertomake,butintherecentyearslotsof2D,3Dframeworksand

Architecture Overview 9

JSB

As mentioned above, JSB contains mapping between javascript and C++ api’s of cocos2d-x, so whenyou choose to deploy your game as native app, all your api’s usage are mapped to actual C++ api’scall with help of spidermonkey, Note that only documented cocos2d-js api’s can be mapped to nativeapi’s call. if you try to invoke any functions internal to cocos2d-js which is not documented, it willwork fine out of the box in browser, however when you deploy it as native app, you may not see thesame result. so it is always recommended to follow the documented api’s if you planning to compileyour game to any mobile platform.

Object Hierarchy

Cocos2d-js is based on object oriented principles, all the entities involved are considered as classand objects. Consider the below figure.

Object Hierarchy

Every class except few utilities in cocos2d-js is inherited from cc.Node, starting from Scene, Layerto Sprites, all are instance of Node object. When ever you deal with any visible elements in cocos2d-js the top most root object is cc.Node. So most of the time you are dealing with Node object. Thederived objects will have its own behaviour and overrides based on their definitions and needs.

Page 14: Rapid Game Development Using Cocos2D-JSsamples.leanpub.com/cocos2d-sample.pdf · Getting Started Introduction Intheearlydays,gamesarehardertomake,butintherecentyearslotsof2D,3Dframeworksand

Architecture Overview 10

Deploy Options

Being a pure javascript library, there is much more options to deploy your app than to rely on cocosconsole.

Deploy as hybrid app

This option is again subjected to your game performance, if your game uses heavy draw cycle thenthis option is not recommended.

Deploy using Titanium

This option will enable you to deploy your app as native app, but feasibility may vary based on whatyou do in your games.

Cocos console

This is the our recommended way to deploy your app to various platforms, you can use othercocos2d-x service such as SDKBOX , pluginX and so on.