All About Cocos2D
Before diving deep into the fun world of game development, we will spend
some time (but only a little) understanding what Cocos2D is, how it can help
you develop games, and why you should use it.
In this chapter, we're going to review the following points:
What a game engine is and why you should use it
Why you should choose Cocos2D as a game engine
A list of games created with Cocos2D
There are several versions of Cocos2D. The original Cocos2D is written
in Python and was first released in 2008. There is also a C++ version
called cocos2d-x, HTML5 version called cocos2d-HTML5, and several
other versions.
In this book, we're going to review the currently most popular version
of Cocos2D, that is, Cocos2D Swift (previously named Cocos2D-iPhone).
However, for brevity, I will just call it Cocos2D.
If in future you will want to learn some other version, it will be quite
easy, because all versions share the same architecture, main concepts,
and a majority of functions.All About Cocos2D
Game engines
Long before the mobile-games era or even PC-gaming era, each game was created for a
specific hardware. This means that if you wanted to create a game, you had to spend some
time learning low-level details of hardware specification and take into account all of its
characteristics, constraints, and sometimes, issues.
Then, when the game was completed and you wanted to create a different game, there was
very little you could reuse from the previous games you created. We're not even speaking
about porting your existing game to another plaorm. In this c tf ase, you just had to rewrite it
almost from scratch.
But hey We're very lucky to live in a different time. A game developer's life is much easier
these days. In our time, we have a lot of different game engines at our disposal; these make
our lives much easier.
So what is a game engine?
A game engine is a software framework that adds a level of abstraction between
hardware, video drivers, sound drivers, and your code. Typical game engines provide
the following functionalities:
Rendering: This is the main function of the majority of game engines. This function
helps you actually draw something on the screen without the need to write any
low-level code. In addition, a game engine sets up a lot of features for you, such as
initializing graphics and loading textures. For example, using a modern game engine,
you can draw a player character on screen with 2-3 lines of code compared to
30-50 lines of code if you're using OpenGL ES 2.0 directly. In addition to static
drawing, game engines provide the ability to animate, scale, rotate, and do many
other useful things just by changing an object property.
User input: There might be a few great games I don't know about, where you don't
have to do anything and don't control the game flow in any way. You just watch what
happens on the screen and enjoy (if you know of such games, let me know). All the
recent popular games take some kind of user input (cutting the rope with a finger
swipe, touching to activate jetpack, and so on). A game engine lets you get that user
input in a convenient manner and respond to it in the game.
8 Chapter 1
Sound: Games with sound are so much beer Adding the righ tt t sound eects and ff
music can turn a mediocre game into a real gem. Again, game engines come to the
rescue and let you play sound eects and backgr ff ound music with only a few lines
of code.
Some game engines provide additional functionalities such as physics engine, collision
detection, scripting, artificial intelligence, networking and multiplayer support, and
localization support. However, many great games were created only using the three
functionalities mentioned earlier.
So what is this all about?
First, it is nice to know that you're lucky to live in a time when you can take a game engine
and concentrate on making great games instead of spending time on learning hardware
specification. So, you have no excuses to not start creating games right now
Second, Cocos2D is a game engine, so it is a good idea to get a basic understanding of a
game engine, its purpose, and its main functions.
Third, many developers including myself love to reinvent the wheel. If you're just beginning
game development and considering whether you should invest your time in learning a game
engine and using it, or learning low-level features such as OpenGL and possibly creating your
own game engine with blackjack, I strongly advise you to start with a game engine such
as Cocos2D.
You will learn a lot of game development concepts, and more importantly, you will be able
to actually make games. After releasing your first game, you will get invaluable experience,
and later, if you decide to dive deeper into low-level details, you will find it much easier aer ft
working with a game engine.
Also, it is nice to know that Cocos2D is based on OpenGL ES 2.0 and won't constrain you in
any way. You will be able to write low-level code where you think it is required, but still leave
all the routine work to Cocos2D.
9 All About Cocos2D
Why Cocos2D?
Now that we have discussed why game engines are good for you, let's have a look why you
should use Cocos2D.
Cocos2D is easy
You can start creating your first game in no time. A few chapters later, you will see this
yourself. Cocos2D has a very beginner-friendly learning curve, and although there is a lot
you can learn about Cocos2D, you can actually start making games and learn as you go.
This is very important, as making games is not about learning advanced tools; it is about
creating a fun and exciting experience for your players. You don't have to master Cocos2D
to create your first game that might reach the top of the AppStore.
Cocos2D is free
Yes, Cocos2D is completely free for commercial use. You will never have to pay anything
for it, and there are a bunch of extensions, utilities, tools, and frameworks that work with
Cocos2D. Of course, there are other free game engines, but some of them just don't reach
the required quality level, and some of them are free only until you start to earn some real
money, and I'm sure you're planning to do that.
I know it is tempting to buy the new, shiny game engine, because you think that if it costs
money, it is beer tt . Well, it is not always true. It is hard to believe, but Cocos2D's quality
can be compared to top-level commercial products, and you still get it for free Even more,
big companies are not only using Cocos2D, but also contributing to it
Cocos2D is popular
Cocos2D has a huge and very responsive community. You will almost never be left alone,
struggling to solve some complicated tasks. A task is either already solved and maybe
even integrated in Cocos2D, or there is a third-party framework or class implementing
the required functionality.
10 Chapter 1
Cocos2D is open source
You can have any opinion about open source projects, but I can assure that you will be
very glad to have access to full source code when things go wrong. When you just start
learning Cocos2D, you will mostly make errors that are easy to spot and fix; we've all
done them. However, later, when you start doing some advanced stuff, having access to
the under-the-hood internals of game engine is just great
Regarding the source code, it is well written, well-structured, and commented. You can
learn a lot just from reading it. In fact, I would suggest every beginner game developer
read it at some point.
Want more?
In addition to all the preceding goodies, you will get the following too:
Physics simulation with the Chipmunk physics engine
Visual tools for building interfaces and levels
Porting to Android with only a few steps
Lots of ready-to-use controls
A lot of other features
Porting to Android has become possible due to eorts of the ff Apportable
company (www.apportable.com), which is a sponsor of Cocos2D project.
They are also providing a great free tool called SpriteBuilder, which definitely
stands out from the rest. High chances that aer some time ft this will be the
only tool you need to develop games for Cocos2D. With SpriteBuilder, you can
design your scenes using GUI editor, create animations, edit physics shapes,
and many more.
However, using SpriteBuilder doesn't eliminate the need to write the code and
understand how Cocos2D works. This is why, I strongly believe that first you
need to learn pure Cocos2D and aer tha ft t it will be very easy to start using
SpriteBuilder and make your life even easier.
Both SpriteBuilder and porting to Android are not covered in this book.
11 All About Cocos2D
Games created with Cocos2D
I'm sure you are wondering if there are any great games created with Cocos2D. The answer
is that there are plenty Let's have look at some of them right now.
This is only the tip of the iceberg. We physically cannot list all the
great games made using Cocos2D, as it will take up a significant part
of the book.
BADLAND
BADLAND is a very atmospheric side-scroller action game with great gameplay and graphics.
BADLAND received a lot of awards (including an award from Apple) and reached the number
one place in more than 80 countries.
The game makes good use of physics and has an amazing design. BADLAND was developed
by a two-man game studio called Frogmind. A screenshot of the game is as follows:
12 Chapter 1
Feed Me Oil 2
Feed Me Oil 2 is a great mind-bending puzzle game, where you need to deliver oil to the
target zone using many different devices. The game reached the top of the AppStore and
was featured in many countries. Its predecessor, Feed Me Oil, was also a great success
The game was developed by an independent game developer, Alexander Ilin. A screenshot of
the game is as follows:
13 All About Cocos2D
Lep's World 2
Lep's World 2 is a really cool and fun plaormer g tf ame with more than 60 million downloads.
The game reached the number one place in several countries and still is very popular. I think
you won't be surprised to know that it was created using Cocos2D. A screenshot of the game
is as follows:
Other games
The listed games here are just a small set of all the games created using Cocos2D. The games
listed earlier were picked because of their quality, high ratings, and to be honest, because I
like them. There are thousands of games created with Cocos2D.
If you don't believe me and want to see a huge list of Cocos2D games, please visit http://
www.cocos2d-iphone.org/games. However, note that this is also not a full list of games,
as it contains only the manually submitted games.
14 Chapter 1
Summary
In this chapter, we've learned some general information about game engines and
Cocos2D in particular. Don't worry if this part seems too abstract; it serves several very
important purposes.
First, you should understand what benefits you get from using game engines, that is, a higher
level of abstraction and faster development at the cost of less control. Don't worry; this cost
is minimal with Cocos2D and in fact, is close to zero as Cocos2D is an open source project.
Also, if you were still deciding whether Cocos2D is the right way to go, this chapter should
have dispelled all doubts. You've seen some examples of great and successful games
developed using Cocos2D. I believe they will inspire you to create your own great and
successful game.
In the next chapter, we're going to use a more practical approach. We will download and
install Cocos2D and will create and run our first Cocos2D project.
15
www.allitebooks.com2
Hello Cocos2D
We learned a bit about Cocos2D in the previous chapter, but it is now time to
get our hands dirty and try it out in action. This chapter covers all the steps
from installing Cocos2D to seeing your first Cocos2D game running. In addition
to this, we're going to review Cocos2D distribution and will see some sample
Cocos2D code in action.
In this chapter, we will complete the following tasks:
Downloading and installing Cocos2D
Creating and modifying our first Cocos2D project
Reviewing the contents of Cocos2D distribution
Running sample projects that come with Cocos2D
Starting with Xcode
Xcode is an Integrated Development Environment (IDE) created by Apple. It provides
everything you need to create apps and games for iOS. In fact, you can even use Cocos2D to
create apps and games for Mac OS X, but this is not covered in this book as we're going to
concentrate on making games only for iOS.
We will use Xcode throughout this book for all of our projects, so if you don't have it installed
yet, you should go and install it now. Downloading and installing Xcode will take some time,
as it is about 2 GB; so, don't delay this and start installing it right away.Hello Cocos2D
Don't worry, it won't cost you a dime. Yes, this great IDE from Apple is completely free and
you can get it easily from the Mac App Store. To install Xcode, go to the Mac App Store (don't
get confused with the iTunes App Store) and search for Xcode, or alternatively, you can just
visit https://developer.apple.com/xcode/downloads/ and click on View on the
Mac App Store.
If you have an Xcode version prior to Xcode 5, you should update to the
latest version. All samples in this book are written and tested in Xcode 5,
and although you shouldn't have problems completing them using later
versions of Xcode 4, it is beer t tt o update just to be on the safe side.
Integrating Cocos2D with Xcode
We'll have to perform a small setup before we can use Cocos2D in our games. This won't
require much of our time or a lot of complicated actions. We only need to download the
Cocos2D installer from the official website and run it. The installer will integrate Cocos2D
with Xcode and add new project templates and documentation.
Time for action – downloading and installing Cocos2D
We're going to install Cocos2D in three easy steps, which are as follows:
1. Head over to http://www.cocos2d-iphone.org/download/ and download the
installer of the latest stable version of Cocos2D.
At the time of writing this book, Cocos2D Version 3.0.0 was the latest
stable version and Version 3.1 was shortly to be released. However, most
of the changes will not affect the code presented. They are mostly feature
enhancements and performance optimizations. Also, the Cocos2D team
stated that they will focus on the backwards compatibility with next
releases, so you should be fine with any later version.
However, keep in mind that even with all the developers' efforts trying
to maintain the backwards compatibility, it is really hard to guarantee
that the next versions will be fully backwards compatible. If you have
any issues with the latest version, you can use the Chapter_02/
Cocos2D+Installer+3.0.0.zip installer that comes with this
book's supporting files (which can be downloaded from www.packtpub.
com/support). Don't worry, switching to the latest version will be easy as
soon as you know all the basics, but it is better to ensure that there are no
differences that cause problems when you're still learning.
18 Chapter 2
2. After the download is complete, unpack the archive and you should see the
Cocos2D Installer 3.0.0.app installer application. Run the installer by
double-clicking on the file.
At this point, you should already have Xcode installed on your
computer. We're going to run the installer in the next step, and
this installer will copy files to the Xcode templates folder
as well as the document set to the library, which is kind of
difficult if you don't have Xcode.
3. The installer will do everything automatically, so all you need to do is sit and wait
until it completes. At the end, you should see something similar to what is shown in
the following screenshot and can close the dialog by pressing the Quit button:
Congratulations, now we have Cocos2D installed and ready to use
19 Hello Cocos2D
What just happened?
We now have everything we need to create Cocos2D games. Mostly this is source code
of Cocos2D and source code of the libraries used by Cocos2D internally. However, the
installer took care of everything, and we didn't have to copy everything manually or
create Xcode templates.
If you had any issues installing Cocos2D, a good place to
search for help is the Cocos2D forum, which can be found
at http://forum.cocos2d-iphone.org/.
Creating a Hello World project
I'm sure you're eager to create a project using the newly installed templates. Let's do this
Time for action – creating a new project from a template
Before starting any serious project, let's create a very simple application using the newly
installed Cocos2D templates, just to feel the taste of it. We'll do this using the following steps:
1. Open Xcode and create a new project by navigating to File New Project. This will
open the project creation dialog. In this dialog, you should see the new cocos2d v3.x
category by navigating to iOS cocos2d v3.x on the left of the screen. Refer to the
following screenshot:
2. Go ahead and select the cocos2d iOS template. After this, click on the Next button.
20 Chapter 2
3. Let's fill out the required information. Enter HelloWorld for the Product Name and
fill out the Organization Name and the Company Identifier fields as you like. The
following is how I filled out the information in this dialog:
Filling out the project options
Right now, you can enter anything in these fields, just to keep
Xcode happy. However, when you want to actually publish your
game in the App Store, you will need to make sure that Bundle
Identifier is a combination of Company Identifier and Product
Name is unique across the App Store.
4. After filling out all the fields, click on the Next button. Save the project anywhere
you like.
It is a good idea to create a folder in Documents or on
your desktop where you will place all your sample projects
for this book. This way, you can easily find them later.
That's it Xcode will do the rest of the job.
What just happened?
You've just created your first project using the Cocos2D template. Using the template
provided by Cocos2D is very convenient. Without this template, we'd have to create an
empty iOS application, add all the required files, frameworks, and libraries, and then write
the Cocos2D initialization code manually each time we want to create a new project.
We will review the contents and structure of the project created via this template later in
Chapter 3, Cocos2D – Under the Hood. Right now, we're going to modify it a little because
I'm sure you're very eager to actually write some code.
However, before writing the code, let's make sure we can run the project.
21 Hello Cocos2D
Testing your projects on a device and simulator
It is a good idea to build and run the project as often as you can, especially while you're
learning. If you've just changed one line of the code and the project doesn't build anymore,
crashes, or there is some kind of a new bug that you didn't notice before, most likely, there
is an error in the line of code you just wrote.
Note that typical real-life projects are quite complicated and the bug you've
just noticed may have been there for some time. Nevertheless, the earlier
you spot it, the less code you will have to review to find the bug. A good way
to spot a bug is to run the project as often as possible.
We're going to follow this tradition and run the project we've just created a few paragraphs
later. Before this, let's review what options we have.
When developing for iOS, you can test your game on a simulator or on an actual device.
Testing on an actual device all the time can be time consuming, as it takes time to install
on the device and copy all resources. However, it is highly recommended to test your game
on an actual device at least from time to time, as it is as close as you can get to the actual
user's device.
Note that there are some bugs that you can catch only when running on a device. For example,
if your game uses a lot of memory, it can run fine on the simulator but will crash on the device.
On the other hand, your game may run slow on the simulator, as there is no hardware
acceleration, but will run smoothly on the device. So, before optimizing your game, try
running it on a device. There are cases when you simply cannot make it run smoothly on the
simulator while it runs great on all the supported devices.
In addition to this, there are some other restrictions when you run your game on the simulator.
For example, there is no convenient way to simulate the accelerometer and gyroscope or
complex multi-touch gestures on the simulator. Although there are some workarounds using
third-party software, it cannot be compared to testing on the actual device, especially in
dynamic games.
You can find more information about the simulator's limitations
at https://developer.apple.com/library/ios/
documentation/IDEs/Conceptual/iOS_Simulator_Guide/
TestingontheiOSSimulator/TestingontheiOSSimulator.html.
(short link: http://bit.ly/1hsORkY).
Despite all limitations, the simulator is a convenient way to test your game, especially in the
early stages.
22 Chapter 2
Don't worry if you don't have an iOS device or an Apple iOS Developer Program membership
right now. Almost all the code in this book can be tested on the simulator. However, if you
plan to actually submit your games to the App Store, it is highly recommended that you have
at least one device to test everything.
To run your projects on devices such as iPhone and iPad, you should be a
member of the Apple iOS Developer Program. At the time of writing this
book, it will cost you 99 a year and will also let you submit your apps to the
App Store and sell your games. You can read more about the program and
enroll at https://developer.apple.com/programs/ios/.
Time for action – running the project on the simulator
The project generated using Cocos2D already contains some code that we can see in action,
so let's make sure that Xcode is targeting the simulator and run the project, before making
any changes. To do this, perform the following steps:
1. Switch to Xcode and take a look at the top-left corner of the Xcode window,
as shown in the following screenshot:
2. Click on the iPhone label marked with the black square as shown in the
previous screenshot. It will open a drop-down list similar to what is shown
in the following screenshot:
23 Hello Cocos2D
3. Here, we can see the different simulators we can run our project on. Let's select iOS
7.1 by navigating to iPhone Retina (4-inch) iOS 7.1 and click on the Run button
(command + R).
If you don't see some of the simulator versions in this
drop-down list, you just don't have them installed. To install
additional simulators, navigate to Xcode Preferences and
select the Downloads tab in the opened dialog.
It will take some time to build a project for the first time and launch the simulator.
After about half a minute, depending on your hardware, you should see the
Cocos2D splash screen followed by the Hello World application generated by the
Cocos2D template, as shown in the following screenshot:
The good thing is that you don't have to close the simulator and
relaunch it every time. Once the simulator is started, you can keep
it running and save a lot of time for the next launches.
24 Chapter 2
Personally, I find iPhone Retina, especially iPad Retina simulators screens,
too big. This shouldn't be surprising as iPad with Retina display has a
screen with a higher resolution than most of the modern displays, unless
you're a lucky owner of the Retina monitor. To make it more convenient
to work with, you can set up the scale of the simulator window. You can
do this by switching to the simulator window and selecting different
options by navigating to Window Scale. You can also find many useful
options in the simulator menu at the top. For example, you may need to
simulate the home button press, the shake gesture, or simply rotate the
simulator window to test the game in different orientations.
What just happened?
Congratulations, you've just run your first Cocos2D game. Don't worry if it feels like magic
right now and you don't feel you are in control, as too much is happening behind the scenes.
After all, we haven't written a single line of code yet.
However, this generated project already does a lot of useful things. We'll see this ourselves
when we review the structure of the Cocos2D project in the next chapter.
I'm sure it feels great to see something on display of the simulator, but you know what, it can
be even beer when y tt ou make some changes to the project
Modifying the project
We're going to create a new view from scratch and will display it instead of the view with the
Hello World label generated by the Cocos2D template.
Time for action – creating a new scene
We will create an empty scene and display it on the screen using the following steps:
1. Switch to Xcode and create a new Objective-C class. To do this, open the Xcode menu
and navigate to File New File and select Cocoa Touch by navigating to iOS Cocoa
Touch on the left of the screen. Then, in the list of templates, select the Objective-C
class item and click on the Next button. Refer to the following screenshot:
25
www.allitebooks.comHello Cocos2D
2. In the next dialog, name our new scene class FirstScene and make it a subclass of
CCScene. After filling out fields in this dialog, as shown in the following screenshot,
click on the Next button:
3. Click on Create and save the files somewhere inside the project folder.
In this book, we will not concentrate too much on organizing
the files that are stored on the disk, and for simplicity,
we will store them in the root of the project folder. If you
prefer organizing files using physical folders, you can create
subfolders within the project folder and save files there.
4. Now that we have the scene, we need to display it. Open the AppDelegate.m file
(it is in the HelloWorld\Classes group) and import the FirstScene.h header,
at the top of the file and just below other import, as follows:
import "FirstScene.h"
5. After importing the header file, search for the startScene method and replace it
with the following:
-(CCScene )startScene
return FirstScene alloc init;
6. Build and run the project. You should see the Cocos2D splash screen displayed for a
few seconds just like before, but then you should see a black screen instead of the
default view generated by the Cocos2D template as follows:
26
Advise:Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.