learn how to make apps for ios, android, blackberry and...

31

Upload: others

Post on 12-Sep-2019

22 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing
Page 2: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

Learn How to Make Apps for iOS, Android,Blackberry and the Web UsingCocos2d-HTML5Make business, marketing and social apps forsmartphones and tablets, like iOS, Android and even Webwith Cocos2d-HTML5

Fernando Altuzar

This book is for sale at http://leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry-and-the-web-using-cocos2d-html5

This version was published on 2013-04-30

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.

©2013 Fernando Altuzar

Page 3: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

To Fany and Isabella

Page 4: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

Contents

1: Cocos2d-Html5 Kamikaze Course . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1tl; dr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Quick Start in 5, 4, 3, 2, 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1What you need . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Get Cocos2d . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Quick Guide to Install MAMP, XAMPP or WAMP . . . . . . . . . . . . . . . . . . . . . . 4Demo Games . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Hello End of the World Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Main Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Deploy (almost) Everywhere . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Pew Pew Pew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

Page 5: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Coursetl; dr

Wrap Cocos2d, JavaScript and HTML5 all together for an app, and deploy it on a Firefox, Chrome,iPhone, and iPad with full native performance. Well, Android was a little bit hash, but we’ll do acomplete chapter for that.

Quick Start in 5, 4, 3, 2, 1

JavaScript and Cocos2d are tecnological outcasts that, all of the sudden, are kinda Kings of theWorld.

Cocos2d started like a humble open source framework created for games. Actually, games for theiPhone. But, open as it is, it was forked and forked to port the ideas behind Cocos2d to otherlanguages and platforms. Now, Cocos2d works on iOS, Android, Windows Phone, Blackberry, Bada,MeeGo, Mac, Windows, Linux and even on web browsers, and can me coded in Objective-C, C++,Lua and JavaScript. Now, it empowers more than half of the games in some countries like China,with very big gaming studios like Electronic Arts or Zynga backing them with blockbuster titles.

And what about JavaScript? Glued in the 90’s by the companies that made the browsers for thatnew tech called Internet, this Frankenstein called “Java” just because Java was best thing ever sincethe electron, and then rebaptized as ECMAscript (that’s the official name), evolved to become themost popular language of the world. Today, it has the loudest young developers using nothing butJavaScript and engines like Node.js, the heart in Google Chrome, to build clients, servers and evenoperating systems.

Well, let’s ride this two outcasts and make your first app. You may enjoy it!

What you need

1. Any text editor.2. Cocos2d-x-HTML5.3. A browser like Firefox, Chrome or Safari.4. A Mac with Xcode and iOS SDK would be very useful too.

I just love when I can develop using my own editor. Nowadays my favorite editor is Sublime Text,but you can use TextWrangler, Textmate, Notepad++, XCode, Eclipse, Vim, Emacs, Nano, Edit, Cat,even Notepad or TextEdit, on Mac or Windows. No problems. And we are open to Linux geeks too!

1

Page 6: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 2

We recommend Sublime Text¹. It’s fantastic.

Get Cocos2d

Well, we won’t develop with Cocos2d for iOS or Android. With those platforms, JavaScript is abinding or bridge that talks with C++, Objective-C or Java, so it’s quite difficult to debug problems.Because of that, we will develop with Cocos2d-HTML5, and use the web browser as main device.Of course, the same code will work perfectly fine on iOS, Android and other platforms too!

So download the latest stable version of Cocos2d-HTML5². That is the Cocos2d-X site, and they arethe coders behind the huge work of adapting the Cocos2d API to other platforms. They are truegenius.

Right now, the latest stable version of Cocos2d-HTML5 is the 2.1.1. I’ll try to keep this book currentwith the updates until the book is released. Promise!

Get familiarized with the site, if you can. Take a look at the Wiki, Reference and Forum tabs. Whilethat big ZIP file is being downloaded, take a look at the Cocos2d-iPhone site³. All the Cocos2dprojects are working together in coordinated releases and documentations tomake a better developerexperience.

Unzip the file and move the folder somewhere in your system. Now do this: open the “index.html”file in that folder. Your browser will open up with a launcher of demos.

¹http://www.sublimetext.com/²http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Download³http://www.cocos2d-iphone.org/

Page 7: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 3

Get ready to be Cocos2dzied.

Clic on the first demo, “Hello World”, and cross your fingers. Eight out of ten times, you will see anice rotating sprite with a “Hello World” and button. Yei! Jump a little bit around!

Page 8: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 4

You are on luck. Hi, Cocos2d-HTML5!

However, sometimes this won’t work, and the will be a blank or black screen. The fastest way tofix this is to try with other browsers. Firefox, Safari and Opera use to work fine. Google Chromeor Internet Explorer, sometimes, don’t work because of security and compatibility issues. Onealternative is to create a webserver. Take a look at the note in the Index of the root folder. InstallingMAMP, XAMPP or WAMP is quite straight forward, but you’ll find a quick guide bellow.

My favorite setup is create a server and open up my “index.html” with Google Chrome and thebrowser’s Developer Tools. But I’ve worked with Firefox and Firebug too without problems.

Quick Guide to Install MAMP, XAMPP or WAMP

If you know Node, Python or have a recent version of PHP, launching a webserver is a one liner.But for the rest of us, here is a very quick guide to install a webserver the classic way. You can findmore (and better) video guides at the YouTube University⁴.

⁴http://www.youtube.com/results?search_query=mamp+OR+xampp+OR+wamp

Page 9: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 5

1. OnMac, downloadMamp⁵ or XAMPP⁶. OnWindows, you can download XAMPP⁷ orWamp⁸.Free versions are OK, but go Pro if you want to support the projects.

2. Install the package. Clic “Continue” or “Next” a couple of times.3. Once installed, open up your http://localhost/ or http://localhost:8000/ (each package has its

default ports) just to see if it’s working. If you see something about Apache, you are good!4. Within the package, change your Document Root and point it to your Cocos2d folder. Then

restart the server. Then refresh your browser and watch, if you had success, the Cocos2d-HTML5 index. Remember: Any problem, YouTube is your friend.

5. You’ve finished!

This is the MAMP main screen.

⁵http://www.mamp.info/en/index.html⁶http://sourceforge.net/projects/xampp/⁷http://sourceforge.net/projects/xampp/⁸http://www.wampserver.com/en/

Page 10: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 6

This is where you can change the Document Root.

Demo Games

Now open up the games just to take a look at them. There are, right now, Moon Warriors, CocosDragon and Crystal Craze. Watermelon With Me is a Box2d sandbox with full physics, ready forcross-platform distribution.

This book is oriented for people wanting to create apps, not games. However, the Cocos2d is a gameengine, even if with it you can create excellent business, marketing or social apps with it. But thereis no waste if we play a little with the resources provided, is it?

Page 11: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 7

Must confess. I’m not that good with this game.

Page 12: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 8

The Moon Warriors are Moon Walker cousins.

Page 13: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 9

I always think, when I see the Dragon in the title, that this is because of Tiny Dragon, but it’s not.

Page 14: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 10

Kinda Bejeweled.

Tests

The Demo Games are excellent on Cocos2d-HTML5; if you want to make games. But if youwant to make apps, they are not very useful. The “Tests” app, in the other hand, is a fantasticsource of resources. Open up the “Test cases” just under the “Hello World” with your browser, or“http://localhost:8888/samples/tests/” if you set the root of your webserver, and take a look at theirapp.

Page 15: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 11

The Tests app is the best resource when you are making any app.

The Tests apps is where the developers behind the Cocos2d-HTML5 project make the, you guess it,tests behind the framework. There is where they take a ride with all the functions of the API. Whenthe testers rise a ticket about any bug, and there are many, someone takes care of it and, sometimes,creates a test proving the bug is fixed.

You can take a look at the Extensions/Cocos Builder tests, to know about the widgets available inCocos2d. Some of them, like buttons, labels and scroll views, are very useful when you create anapp.

As you may see, some of the tests could not be available yet. Those are ready for other platforms likeiPhone and Android, but not for HTML5. Don’t worry about it. You don’t need advanced graphicfeatures like “Render Texture Tests”. You just want to make simple apps!

Finally, open up the “samples/tests” folder with Finder or Explorer. There is all the code you willever need! Well, with Cocos2d you will need a couple of native bridges to open browsers and othernative widgets. But we’ll take care of that later. Don’t be impatient!

Page 16: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 12

Hello End of the World Setup

After you have seen the Cocos2d websites and the Demo and Tests examples and code, you areready to create your first project. Some of this examples are taken from the Cocos2d-X site, wikiand forums, and from RayWenderlich.com⁹ site. I love their materials!

Copy the “HelloHTML5World” folder from your Cocos2d-HTML5 installation somewhere in yoursystem, I chose the Desktop, but you can place it in your Document Root folder. Rename it to “HiEnd-OfTheWorld” or anything you want. Delete the files in there (only the files, not the directories!),and delete the “src/myApp.js” too. We will create our own versions of them. Then create a foldercalled “platform” in it, and inside “platform” create four subdirectories called “Android”, “HTML5”,“iOS” and “OSX”. Finally, copy the “cocos2d”, “CocosDenshion” and “extensions” directories fromyour Cocos2d-HTML installation into the “HTML5” folder you just created. Bear with me. This willbe the ultimate setup to create all your projects with Cocos2d. Your folder should look like this:

You are almost ready to begin coding. Relax!

To create your first template, we’ll create 4 files. The first one, you may guess it, is “index.html”.Create it in your root like.

⁹http://www.raywenderlich.com/

Page 17: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 13

1 <!DOCTYPE html>

2 <html>

3 <head>

4 <meta charset="utf-8">

5 <title>Cocos2d-HTML5 Viewer</title>

6 <link rel="icon" type="image/GIF" href="res/favicon.ico"/>

7 </head>

8 <body style="text-align: center;background: #4A525A;">

9 <div></div>

10 <div style="display:inline-block;width:auto; margin: 0 auto; background: bl\

11 ack; position:relative; border:5px solid black; border-radius: 10px; box-sh\

12 adow: 0 5px 50px #333">

13 <canvas id="gameCanvas" width="800" height="450"></canvas>

14 </div>

15 </body>

16 </html>

17 <script src="cocos2d.js"></script>

Let me explain. The only important lines are the

Then, create the “cocos2d.js” file in that directory. Add this code in it.

1 (function () {

2 var d = document;

3 var c = {

4 COCOS2D_DEBUG:2, //0 to turn debug off, 1 for basic debug, and 2 fo\

5 r full debug

6 box2d:false,

7 chipmunk:false,

8 showFPS:true,

9 frameRate:60,

10 loadExtension:true,

11 tag:'gameCanvas', //the dom element to run cocos2d on

12 engineDir:'./platform/HTML5/cocos2d/',

13 //SingleEngineFile:'',

14 appFiles:[

15 './src/resource.js',

16 './src/MainLayer.js',

17 './src/main.js'

18 ]

19 };

20 window.addEventListener('DOMContentLoaded', function () {

21 //first load engine file if specified

Page 18: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 14

22 var s = d.createElement('script');

23 /*********Delete this section if you have packed all files into one\

24 *******/

25 if (c.SingleEngineFile && !c.engineDir) {

26 s.src = c.SingleEngineFile;

27 }

28 else if (c.engineDir && !c.SingleEngineFile) {

29 s.src = c.engineDir + 'platform/jsloader.js';

30 }

31 else {

32 alert('You must specify either the single engine file OR the en\

33 gine directory in "cocos2d.js"');

34 }

35 /*********Delete this section if you have packed all files into one\

36 *******/

37

38 //s.src = 'Packed_Release_File.js'; //IMPORTANT: Un-comment thi\

39 s line if you have packed all files into one

40

41 document.ccConfig = c;

42 s.id = 'cocos2d-html5';

43 d.body.appendChild(s);

44 //else if single file specified, load singlefile

45 });

46 })();

That is a boilerplate to create a launcher, and almost all of it comes from the “cocos2d.js” file in theHelloWorld folder. Then why did I delete it!, you may ask. Well, we changed lots of things and andany error may crash all your app, so we thought it would be better to recreate it.

Within the changes:

1. Load the extensions.2. Set the engineDir to your platform/HTML5/cocos2d folder. This is crucial!3. Add the 3 files for your app.4. Set the s.src loader as “platform/jsloader.js”. This is crucial too!

As you can see, this is a very important file. There you load complements like Box2d or Chipmunk,for physics, set the frame rate and debug level, and load the necessary files.And this is your firstJavaScript file. Don’t worry, it gets nicer.

Now go to your src folder. We are almost done with configuration files. Just take a look at“resource.js”. There you declare all your assets. It’s important because all those files are added to

Page 19: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 15

the iOS and Android projects too, and there you must declare the assets like images, fonts, soundsof effects.

Must tell you, I’m not that fan of adding my resources to this file. I love place my images withinmy code and just display it with a line. Let’s hope in the future we don’t have to do this. Cross yourfingers!

Now create the file “main.js” and add this code:

1 var cocos2dApp = cc.Application.extend({

2 config:document['ccConfig'],

3 ctor:function (scene) {

4 this._super();

5 this.startScene = scene;

6 cc.COCOS2D_DEBUG = this.config['COCOS2D_DEBUG'];

7 cc.initDebugSetting();

8 cc.setup(this.config['tag']);

9 cc.Loader.getInstance().onloading = function () {

10 cc.LoaderScene.getInstance().draw();

11 };

12 cc.Loader.getInstance().onload = function () {

13 cc.AppController.shareAppController().didFinishLaunchingWithOpt\

14 ions();

15 };

16 cc.Loader.getInstance().preload(g_ressources);

17 },

18 applicationDidFinishLaunching:function () {

19 var director = cc.Director.getInstance();

20 director.setDisplayStats(this.config['showFPS']);

21 director.setAnimationInterval(1.0 / this.config['frameRate']);

22 director = cc.Director.getInstance();

23 winSize = director.getWinSize();

24 centerPos = cc.p( winSize.width/2, winSize.height/2 );

25 director.runWithScene(new this.startScene());

26 return true;

27 }

28 });

29 var director;

30 var winSize;

31 var centerPos;

32 var myApp = new cocos2dApp(MainLayer.scene);

There you load config files and create the Director (we will talk about him on Chapter 3). The

Page 20: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 16

Director is very important. He has even a chapter for him alone! You create a couple of utilitaryvariables too, like winSize and centerPos.

Main Layer

Finally, create the application file. We are almost ready, I swear!

1 var MainLayer = cc.LayerColor.extend({

2 ctor:function() {

3 this._super();

4 cc.associateWithNative( this, cc.LayerColor );

5 },

6 onEnter:function () {

7 this._super();

8

9 var bg = cc.Sprite.create(s_HelloWorld);

10 bg.setPosition( winSize.width / 2, winSize.height / 2);

11 this.addChild(bg);

12 }

13 });

14

15 MainLayer.create = function () {

16 var sg = new MainLayer();

17 if (sg && sg.init(cc.c4b(255, 255, 255, 255))) {

18 return sg;

19 }

20 return null;

21 };

22

23 MainLayer.scene = function () {

24 var scene = cc.Scene.create();

25 var layer = MainLayer.create();

26 scene.addChild(layer);

27 return scene;

28 };

We’ll explain later. Now, double clic the “index.html” or go to your localhost and location with yourbrowser. You should see the Cocos2d-HTML5 logo and some performance numbers. You did it!

If there is a problem, stay calmed. Double check your MAMP configuration, open the “index.html”directly with other browsers or look to console errors in Firefox’s Firebug or Google Chrome’sDeveloper Tools. We’ll talk a little bit about those resources in the Chapter 3, so take a peek! There

Page 21: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 17

may be a typo or missing file. Remember there is the Ultimate Cocos2d-HTML5 Source Code Packfor Pixel Perfect Apps TM available with all the source code used in this book at our site¹⁰. Thisshould be your complete folder by now:

Ready to go!

Now let’s take a look to your MainLayer.js. The language is JavaScript. We’ll talk a little more aboutJavaScript in Chapter 2, but it is a very readable and simple language. Almost all of that file isboilerplate, and will be reusable in every layer. That is: in every screen.

A word about nodes. In Cocos2d, a layer is a node. An image is a node. A label is a node. Actually,anything on the screen is a node, and it’s the most basic particle in Cocos2d. Because everything isa node!

Any layer, and a layer that covers all the screen in a modal way, is an extension of a Cocos2d classcalled LayerColor. So, you create it like:

1 var MainLayer = cc.LayerColor.extend({ ... });

By the way, “cc” is for Cocos2d, and any Cocos2d class will start with “cc”.

¹⁰http://appskai.com/cocos2dhtml5

Page 22: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 18

The rest of the code is only to create the layer properly, so it can be destroyed nicely when you needto replace it with another layer or screen. All the code about what is shown on the layer is in the“onEnter” function, and it’s placing one of the images declared in “resource.js”:

1 var bg = cc.Sprite.create(s_HelloWorld);

2 bg.setPosition( winSize.width / 2, winSize.height / 2);

3 this.addChild(bg);

There, you create a sprite, that is an image, taken from s_HelloWorld as declarated in “resource.js”.Then set the position in the center of the screen and, finally, add the image to the layer. That way,when the layer is destroyed, that image will be destroyed and the memory released.

Remember “main.js”? There we created a variable called “centerPos” as the center of the screen. Thatline was:

1 centerPos = cc.p( winSize.width/2, winSize.height/2 );

The class “cc.p” is something like a coordinate of the screen. We’ll be using it a lot, so get comfywith it! I used winSize.width and winSize.height to make it clear, but we should use our “centerPos”variable, don’t you think? So change it in your code:

1 var bg = cc.Sprite.create(s_HelloWorld);

2 bg.setPosition( centerPos );

3 this.addChild(bg);

When you reload, everything should be exactly the same!

Now create a nice label at the bottom of the screen to celebrate that the End of the World didn’tarrived. Add this below the background, in the “onEnter” function:

1 var lb = cc.LabelTTF.create("Hi, End of the World", "Arial", 38);

2 lb.setPosition(cc.p( winSize.width / 2, winSize.height * 0.1 ));

3 this.addChild(lb, 5);

Because we are showing images on a OpenGL space, the y axis is upside down. Meaning, 0 is thebottom of the canvas and winSize.height is the top. Hope it makes sense.

Reload the browser and it should have our not so nice label.

Page 23: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 19

Label up and running.

But you don’t like that pale color? Let’s change the color then, just to make it nicer. Add this to theend of the “onEnter” function:

1 lb.setColor(cc.c3b(255, 0, 0));

When you reload the screen, you should find the label with a red color.

Page 24: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 20

Redrum, redrum.

As you can see, it’s possible to change the node, sprite or label after it has been added to the layer.With that class, “cc.c3b”, you create a Cocos2d RGB color. You can have a fourth alpha channel with“cc.c4b”.

We are done with it. For now. Time to deploy!

Deploy (almost) Everywhere

I’ll be honest with you. We will deploy to iOS, but we’ll leave Android and other platforms for later.Android is so important (and difficult to deploy to, using Cocos2d-HTML5 at least) that it will haveits own chapter. Isn’t that awesome?

iOS aka iPhone

If you don’t have Cocos2d already installed, download the latest unstable version at their site¹¹.

¹¹http://www.cocos2d-iphone.org/download

Page 25: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 21

Don’t worry if it says unstable. It’s quite usable.We used Cocos2d-iPhone-2.1-rc1 version. Downloadit and unzip it. Then, install it going to the directory where you unzipped it with your Terminal andenter:

1 ./install-templates.sh -f -u

Then you’ll see a lot of lines and finally a “done!”. That means you are done!

Now open Xcode and go to “Create a new Xcode project”.

Did you know that Xcode is called like that because of the XFactor?

And create a iOS -> cocos2d v2.x -> cocos2d iOS with JavaScript template.

Page 26: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 22

Nice templates in there. Take a look at them when you can.

Name the project “HiEndOfTheWorld” and add your name and identifier. Or just anything youwant.

Page 27: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 23

Your future Forbes 100 company goes here.

And save it in the HiEndOfTheWorld/platform/iOS folder. Do you see where we are going to?

Page 28: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 24

iOS almost ready.

Now, from Finder, drag your “res” and “src” folders into your Xcode project. That would be thefolder below the target. When the popup that appears, choose “Create folder references for anyadded folders”. This is very important, so take notice of it!

Page 29: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 25

Drag, drop and create folder references.

The final proyect structure in Xcode should be the following. Look the blue folders below the yellowone. That means they are referenced. If they are not like this, delete them and try again.

Yellow folder, blue folder.

One little step and we are done. Open “Resources/main.js” and replace the contents with thefollowing code:

Page 30: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 26

1 require("jsb.js");

2 require("src/resource.js");

3 require("src/MainLayer.js");

4

5 director = cc.Director.getInstance();

6 winSize = director.getWinSize();

7 centerPos = cc.p( winSize.width/2, winSize.height/2 );

8

9 function run()

10 {

11 director.runWithScene( MainLayer.scene() );

12 }

13

14 run();

Compare that code with the main.js for the browser. They are quite similar, don’t you think?

Now run it on your iOS Simulator or deploy it to your iPhone or iPad. You did it!

This is an iPhone 5. Or Retina 4-inch. Believe me!

Page 31: Learn How to Make Apps for iOS, Android, Blackberry and ...samples.leanpub.com/learn-how-to-make-apps-for-ios-android-blackberry... · LearnHowtoMakeAppsforiOS,Android, BlackberryandtheWebUsing

1: Cocos2d-Html5 Kamikaze Course 27

Pew Pew Pew

Well, maybe it was a little more than 5 minutes, but you created this little app for web and iOS and,remember, this code will work on Android, Mac and other platforms too in the next chapters.

Next, a short, fast and incredibly complete JavaScript for Cocos2d Kamikaze Course!