Cocos2d Cross-Platform Game Development Cookbook - Second Edition - Siddharth Shekar - E-Book

Cocos2d Cross-Platform Game Development Cookbook - Second Edition E-Book

Siddharth Shekar

0,0
43,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Develop games for iOS and Android using Cocos2d with the aid of over 70 step-by-step recipes

About This Book

  • Learn to efficiently use Cocos2d to develop cross-platform games, and have them work on iOS as well as Android
  • Get acquainted with industry-wide professional tools such as Glyph Designer, Texture Packer, and Physics Editor, as well as using the Swift/ Sprite builder implementation of Cocos2d
  • Use the easy-to-follow recipes to develop as well as deploy games to the Playstore and the App Store

Who This Book Is For

This book is for intermediate game developers and especially the ones who are generally curious to find out what's new in Cocos2d v 3.3.

What You Will Learn

  • Build custom sprites with custom animations for the game
  • Build interactivity into your game by adding gestures and touch interactions
  • Understand AI enemy programming and path finding to make games more exciting
  • Add physics to your game to make it more lively and interactive
  • Get familiar with the Swift and Sprite builder implementations along with Objective-C programming
  • Perform hassle-free deployment of games built in iOS onto Android
  • Add effects and particle systems to make the game more colorful

In Detail

Cocos2d is the world's leading game development framework for developing iOS games. With the introduction of Swift and Spritebuilder, it has become easier than ever to develop the games of your dreams without much effort. With Cocos2d, you can also deploy the game on Android, thereby maximizing profit and reducing development and porting costs.

The book starts off with a detailed look at how to implement sprites and animations into your game to make it livelier. You will then learn to add scenes to the game such as the gameplay scene and options scene and create menus and buttons in these scenes, as well as creating transitions between them. From there on, you will get an understanding of how to program user interactions such as tapping, holding, and swiping. You'll then add accelerometer inputs and physics to the scene, and make objects respond back to the inputs. A game is practically incomplete without audio being added, so this will be covered next.

The next section will include ways to add Artificial Intelligence to enemies in the game, allowing them to patrol, chase, and shoot in a projectile manner. You will then learn to use NSUserDefault to save and load game progress, and create and access files using JSON, Plist, and XML files for custom storage and retrieval of data. Then you will learn to add dynamic lighting to your game and will use industry-wide tools such as Texture Packer, Glyph Designer, Physics Editor, Particle Designer, and Sprite Illuminator to create more visually appealing and performance-optimized games.

Towards the end of the book, we dive into Apple's latest programming language—Swift, highlighting the major differences between Objective C and Swift. The book culminates with taking your existing game developed for iOS and porting it to Android, showing you how to install the Android Xcode plugin as well.

Style and approach

The book is written in an extremely lucid and step-by-step manner; it can be understood easily by anyone. The topics included are broken down into individual chapters so you can refer to the specific chapter to get answers on the subject you are interested in.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 295

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Cocos2d Cross-Platform Game Development Cookbook Second Edition
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
eBooks, discount offers, and more
Why Subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Sprites and Animations
Introduction
Downloading and installing Cocos2d
Getting ready
How to do it…
How it works…
The 2D coordinate system
Getting access to MainScene
Getting ready
How to do it…
How it works…
Adding sprites to scenes
Getting ready
How to do it…
How it works…
Creating a sprite using RenderTexture
Getting ready
How to do it…
How it works…
There's more…
Creating a custom sprite class
Getting ready
How to do it…
How it works…
Animating sprites
Getting ready
How to do it…
How it works…
Adding actions to sprites
Getting started
How to do it…
How it works…
There's more…
Drawing glPrimitives
Getting ready
How to do it…
How it works…
There's more…
Adding the parallax effect
Getting ready
How to do it…
How it works…
2. Scenes and Menus
Introduction
Adding a MainMenu Scene
Getting ready
How to do it…
How it works…
Adding text using CCLabel
Getting ready
How to do it…
How it works…
There's more…
Adding buttons with CCMenu
Getting ready
How to do it…
How it works…
Adding a Gameplay Scene
Getting ready
How to do it…
How it works…
Transitioning between scenes
Getting ready
How to do it…
How it works…
There's more…
Adding transition effects
Getting ready
How to do it…
How it works…
There's more…
Adding a Level Selection Scene
Getting ready
How to do it…
How it works…
Scrolling a Level Selection Scene
Getting ready
How to do it…
How it works…
3. Gestures, Touches, and the Accelerometer
Introduction
Understanding swipe
Getting started
How to do it…
How it works…
There's more…
Implementing tap
Getting started
How to do it…
How it works…
Adding LongPress
Getting ready
How to do it…
How it works…
Adding pinch/zoom controls
Getting ready
How to do it…
How it works…
Adding rotation objects
Getting ready
How to do it…
How it works…
Adding panning
Getting ready
How to do it…
How it works…
Including touches
Getting ready
How to do it…
How it works…
Creating objects with touchBegan
Getting ready
How to do it…
How it works…
There's more…
Moving objects with touchMoved
Getting ready
How to do it…
How it works…
Customizing touches in the sprite class
Getting ready
How to do it…
How it works…
Adding an accelerometer
Getting ready
How to do it…
How it works…
Adding a directional pad
Getting ready
How to do it…
How it works…
There's more…
4. Physics
Introduction
Adding physics to a game scene
Getting started
How to do it…
Adding physics objects
Getting started
How to do it…
How it works…
Looking at different body types
Getting started
How to do it…
How it works…
Adding sprite texture to physics objects
Getting started
How to do it…
How it works…
Creating composite bodies
Getting started
How to do it…
How it works…
Creating complex shapes
Getting started
How to do it…
How it works…
Changing body properties
Getting started
How to do it…
How it works…
There's more…
Applying impulse with the touch control
Getting started
How to do it…
How it works…
Applying force with the accelerometer
Getting started
How to do it…
How it works…
Collision detection
Getting started
How to do it…
How it works…
Adding revolute joints
Getting started
How to do it…
How it works…
Adding motor joints
Getting started
How to do it…
How it works…
Adding a game loop and scoring
Getting ready
How to do it…
How it works…
5. Audio
Introduction
Adding background music
Getting ready
How to do it…
How it works…
Adding audio effects
Getting ready
How to do it…
How it works…
Adding a mute button
Getting ready
How to do it…
How it works…
Adding a volume slider
Getting ready
How to do it…
How it works…
Adding a pause and resume button
Getting started
How to do it…
How it works…
6. AI and A* Pathfinding
Introduction
Patrol enemy behavior
Getting ready
How to do it…
How it works…
Projectile shooting enemy
Getting ready
How to do it…
How it works…
Chasing enemy behavior
Getting ready
How to do it…
How it works…
A* pathfinding
Getting ready
How to do it…
How it works…
7. Data Storage and Retrieval
Introduction
Loading the XML file data
Getting started
How to do it…
How it works…
Saving to the XML file data
How to do it…
How it works…
Loading the JSON file data
Getting ready
How to do it…
How it works…
Loading the PLIST file data
Getting ready
How to do it…
How it works…
Saving the PLIST file data
Getting ready
How to do it…
How it works…
Using NSUserDefaults
How to do it…
How it works…
8. Effects
Introduction
CCEffects
Getting ready
How to do it…
Adding the bloom effect
Adding the blur effect
Adding the brightness effect
Adding the drop shadow effect
Adding the pixelate effect
Adding the stack effect
How it works…
Adding the glass effect
Getting ready
How to do it…
How it works…
Adding the motion streak effect
Getting ready
How to do it…
How it works…
Adding the particle effect
Getting ready
How to do it…
How it works…
There's more…
Adding 2D lighting
Getting ready
How to do it…
How it works…
There's more…
9. Game Tools
Introduction
Glyph Designer
Getting ready
How to do it…
How it works…
Particle system
Getting ready
Particle Designer
Emitter configuration
Particle Settings
Color settings
Texture settings
Particle2dx
Motion
Color&Shape
Template
Export
How to do it…
How it works…
TexturePacker
Getting ready
Data
Texture
Layout
Sprites
How it works…
PhysicsEditor
Getting ready
How to do it…
How it works…
10. Swift/SpriteBuilder Basics
Introduction
Implementing the Swift syntax
Getting started
How to do it…
Variables
Operators
Arithmetic operators
Comparison operators
Logical operators
Arithmetic increment/decrement and assignment operations
Control flow statements
Decision making statements
The if statement
The if else statement
The else if statement
The conditional expression
The switch statement
Looping statements
The while loop
Repeating the while loop
The for loop
The for in loop
Arrays
Looping through arrays
Adding, removing, and inserting objects in arrays
Important array functions
Dictionary
Adding and removing objects in a dictionary
Looping through items in a dictionary
Dictionary functions
Functions
Simple functions
Passing a parameter
Passing more than one parameter
Returning a value
Default and named parameters
Returning more than one value
Classes
Properties and initializers
Custom methods
Inheritance
Access specifiers
Optionals
Implementing Cocos2d Swift
Getting ready
How to do it…
How it works…
SpriteBuilder basics
Getting ready
How to do it…
How it works…
11. Porting to Android
Introduction
Installing the Android Xcode plugin
Getting started
How to do it…
Enabling USB debugging on a device
How to do it…
Running the SpriteBuilder project on a device
How to do it…
Porting a project to Android
How to do it…
No Java runtime error
How to do it…
Provision profile error
How to do it…
Blank screen error
How to do it…
Useful resources
Index

Cocos2d Cross-Platform Game Development Cookbook Second Edition

Cocos2d Cross-Platform Game Development Cookbook Second Edition

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: May 2015

Second edition: February 2016

Production reference: 1120216

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78439-323-6

www.packtpub.com

Cover image by Siddharth Shekar

Credits

Author

Siddharth Shekar

Reviewers

Hsiao Wei Chen

Tim Park

Commissioning Editor

Ashwin Nair

Acquisition Editors

Shaon Basu

Kevin Colaco

Content Development Editor

Akshay Shetty

Technical Editor

Humera Shaikh

Copy Editor

Shruti Iyer

Project Coordinator

Sanchita Mandal

Proofreader

Safis Editing

Indexer

Mariammal Chettiyar

Production Coordinator

Conidon Miranda

Cover Work

Conidon Miranda

About the Author

Siddharth Shekar is a game developer with over 5 years of industry experience in game development. He has developed several games and published them on the iOS, Android, Amazon, and Windows Phone App Stores.

Siddharth has been programming for the last 11 years and is adept at C++, C#, Objective-C, Java, JavaScript, LUA, and now Swift. He has experience in developing games for the web, mobile, and desktop using Flash, Cocos2d, Cocos2d-x, Unity 3D, and Unreal Engine. Siddharth has also worked with graphics libraries such as DirectX, OpenGL, and OpenGL ES.

Apart from developing games, he also conducts game development workshops in major engineering colleges and is a visiting faculty in game development institutes.

Siddharth is also the author of the books Learning Cocos2d-x Game Development and Learning iOS 8 Game Development Using Swift, both published by Packt Publishing.

Currently, he is a lecturer in the game department of Media Design School, Auckland, New Zealand, where he teaches graphics programming and PlayStation 4/PS Vita native game development and mentors final year production students.

In his spare time, Siddharth likes to experiment with the latest game development frameworks and tools. Apart from being an avid gamer, he is interested in animation, computer graphics, and music, and is an absolute movie buff.

More information about Media Design School and Siddharth Shekar can be found at www.mediadesignschool.com.

Acknowledgments

As always, I would like to first and foremost thank my mom, Shanti Shekar, and dad, R. Shekar, for their continuing unconditional love and support.

I would like to thank Fiona Scott-Milligan, chief academic officer, and Syed Fawad Mustafa Zaidi, program coordinator, at Media Design School for encouraging me to continue working on the book. Many thanks to my colleagues at the Bachelor of Software Engineering Department—Asma, Salwan, Bindu, Imran, Shilpa, and Michael—for supporting me through the book writing process.

I can't thank enough Andreas from CodeAndWeb and Tom from 71Squared for their awesome tools as I would have spent most of my time developing the tools rather than making games otherwise.

I would also like to thank Packt Publishing for putting this book together. I would like to thank Adrian Raposo, Akshay Shetty, and Samantha Gonsalves for helping and guiding me at every step of the book writing process. Thanks to the technical reviewers for their technical feedback and tips; I have really learned a lot of new things in this process.

Finally, I would like to thank my friends, followers, and well-wishers for being a part of my life and tolerating me all these years.

About the Reviewers

Hsiao Wei Chen makes games for mobile devices using Unity, Cocos2d, and native code. She has also participated in a game jams, in which she attempted to create a game in 48 to 72 hours. Hsiao enjoys writing, and has taken part in NaNoWriMo, in which she attempted to write a 50,000-word novel in a month. She is also a blogger and writes tutorials and book reviews.

I would like to thank my two sisters and my parents who support me in everything that I choose to do.

Tim Park started programming in BASIC on VIC-20, moved on to C on Amiga, and then to other languages and frameworks that let him get things done. He started programming professionally on accounting systems, then on videogame consoles, and currently works on mobile and web development at Arctic Empire.

www.PacktPub.com

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why Subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Preface

Since its inception in 2007, the Apple App Store is still going strong with an average of almost 500 apps added on a daily basis. Out of them, almost 80% of the apps are games. Part of the reason for this is the amazing eco-system created by Apple to make the operating system and IDE available free of charge, making it easy to access for the average developer. The other part is Cocos2d, which is still one of the most widely-used free iOS game-development frameworks that makes games and app development very convenient.

With SpriteBuilder integrating Cocos2d into it, this makes it even more awesome, as now it is even easier to develop a simple prototype of a game without any code. Moreover, with minimum effort the same app or game can be run on a varied number of resolutions. Furthermore, we can now also port these games to Android without any need to rewrite the code. Cross-platform iOS game development, which was a dream for so many years, has now finally become a reality.

As Cocos2d itself has been there since the beginning of the first iOS device, the community is strong and helpful. There are also great tools that have been developed by third-party developers that make Cocos2d, an already awesome framework, even more awesome.

This book takes you through the recipes that are required to make any game. The chapters are laid out in a logical manner so that by following each recipe you will get closer to finishing and porting your game by the end of this book.

Hope to see your creations in the App Store soon.

What this book covers

Chapter 1, Sprites and Animations, teaches you how to draw sprites in a scene, add colored sprites, and render 2D shapes using primitives. This chapter will also show you how to animate sprites, move sprites, add different kinds of actions to a sprite, and also look at the parallax effect to create a more dynamic scene.

Chapter 2, Scenes and Menus, will cover how to add scenes to the game, such as a gameplay scene, how to create buttons and labels in the scene, and how to create transitions between the scenes using various transition effects.

Chapter 3, Gestures, Touches, and the Accelerometer, will discuss various methods of user interaction, such as tapping, holding, swiping along with adding accelerometer inputs and gestures to the scene.

Chapter 4, Physics, will provide examples of how to add physics to the scene and make objects respond to physics. This chapter will also look at different body types and body properties, adding sprites to a body, applying force and impulse to a body, detecting collision responses, and building objects, such as a vehicle, by adding physics bodies together.

Chapter 5, Audio, will show you how to edit audio tracks to create music and sound effects, add the background music and audio effects to the game, add a pause and resume button to the game, and add a volume slider to control the volume of audio to the options menu.

Chapter 6, AI and A* Pathfinding, will include ways to add Artificial Intelligence to enemies in the game. This chapter will also look at creating patrolling, chasing, and projectile shooting enemies. It will cover a pathfinding to create more advanced AI logic for enemies using grids.

Chapter 7, Data Storage and Retrieval, will teach you how to save and load game progress on the device using NSUserDefault, create and access files using JSON, Plist, and XML files, for custom storage and retrieval of data.

Chapter 8, Effects, teaches you to add dynamic lighting to your game, manipulate the position and color of the light source dynamically using touch controls, and add 2D shadows to the game created by the light source. You will learn to add effects to the game using the CCEffects class of Cocos2d to create interesting effects in the game.

Chapter 9, Game Tools, provides insights to using industry standard tools, such as TexturePacker, Glyph Designer, PhysicsEditor, Particle Designer, and Sprite Illuminator, to create more visually appealing and performance-optimized games.

Chapter 10, Swift/SpriteBuilder Basics, shows you how to develop games in Apple's latest programming language, Swift. We will see the differences between Objective-C and Swift in this chapter. We will also see how to import Objective-C classes into Swift to reduce the redundancy of code. This chapter will also provide insight into using SpriteBuilder to develop more robust games.

Chapter 11, Porting to Android, will take a look at how to take your existing game developed for iOS and port it to Android. We will learn how to install the Android Xcode plugin, prepare the device for deployment, and finally run the project on an Android device.

What you need for this book

To develop games using Cocos2d, all you need is the latest version of OSX El Capitan, SpriteBuilder, and Xcode. All these applications are available in the Apple App Store and are free to download. The recipes in this book are designed for iPads, so iPad 3 onwards can be used for testing purposes. To develop on Android, an Android device is required. It is better to use the Galaxy or Nexus series phones as they are tried and tested.

Who this book is for

The structure of the book is designed in such a way that it is easy to access a specific recipe and get the necessary information from it. Each recipe is self-contained and easy to follow. This book is for intermediate to advanced users who have some basic knowledge of how Cocos2d works. Although the basic concepts are covered in this book, they are not explained in depth, so some prior experience is required.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it…, How it works…, There's more…, and See also).

To give clear instructions on how to complete a recipe, we use these sections as follows:

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We will then create the _sprite1 and _sprite2 variables. In spriteWithImageNames, we will pass the filename variable that will hold the string of the filename."

A block of code is set as follows:

#import "CCSprite.h" @interface ParallaxSprite :CCSprite{ CGSize _winSize; CGPoint _center; CCSprite *_sprite1, *_sprite2; float _speed; } -(id)initWithFilename:(NSString *)filename Speed:(float)speed; -(void)update:(CCTime)delta; @end

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

#import "Hero.h" #import "ParallaxSprite.h" @interface MainScene :CCNode{ CGSizewinSize; Hero* hero; ParallaxSprite* pSprite; }

Any command-line input or output is written as follows:

./install.sh -i

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Next, we will give it a class name. We will select CCSprite as Subclass of and Objective–C as Language."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/Cocos2dCrossPlatformGameDevelopmentCookbookSecondEdition_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Sprites and Animations

The topics covered in this chapter are as follows:

Downloading and installing Cocos2dThe 2D coordinate systemGetting access to MainSceneAdding sprites to scenesCreating a sprite using RenderTextureCreating a custom sprite classAnimating spritesAdding actions to spritesDrawing glPrimitivesAdding the parallax effect

Introduction

In the first chapter, we will cover some basics of the Cocos2d framework so that everyone is up to speed on the concepts. We will go through the process of downloading and installing SpriteBuilder/Cocos2d. Then we will cover the 2D coordinate system that Cocos2d uses.

After going through the basics, we will cover the basic properties of sprites and how they can be added to a scene. We will take a look at how to add an image to a sprite object. We will discuss how to create a sprite that is used as placeholder asset to test basic game mechanics and collision in the prototyping stage of any game. We will then consider how to create basic shapes using glPrimitives. After this, we will move on to discussing how to move, rotate, scale, and combine actions on the sprite object using actions. Next, we will look at how to animate a character using sprite frames. Finally, we will add parallax scrolling to the scene to add more dynamism to it.

Downloading and installing Cocos2d

To create and run a Cocos2d project, you have to install SpriteBuilder and Xcode. In this section, we will briefly cover how to do so.

Getting ready

To download and install Cocos2d, go to http://cocos2d.spritebuilder.com/download.

SpriteBuilder is the official installer of Cocos2d now. To install, click on the Cocos2d-SpriteBuilder installer link. This will open the Mac App Store Preview page.

If you would like to download an older version of Cocos2d, you can go through the links in the archive section of the page and download it from there as well.

Click on the View in Mac App Store link and then click on Launch Application when prompted.

Once the App Store opens, click on Install to start the installation process. You will need to sign in to an account to download the file.

Once installed, it should be in your applications folder. Open up Launchpad and click on the application to open it.

Once the application starts, you will be asked to join the SpriteBuilder mailing list. Add your e-mail address and click on Continue or select Sign Up Later.

We will go through how to create a small project using SpriteBuilder later in the book. For now, we are ready to create a new project to work with. Navigate to File | New Project and select a location to create the project folder.

You can also select the primary language for coding. As we will use Objective-C, make sure that it is selected at the bottom.

Once you have selected the location for the project, in the Save As box at the top, give the project a name. Remember the name and the location of the project folder as we will need it to open the project in Xcode.

Next, we need to open the project in Xcode. We will first understand how to code using Xcode as it is essential to make more complex games. In later chapters, we will consider how to use SpriteBuilder to simplify our game development process.

You can close the SpriteBuilder project as it is not required anymore.

If you don't have Xcode, you can download it from the Mac App Store.

The installation process is very similar to any other app.

How to do it…

Perform the following steps:

Once you install Xcode, go the to the project folder in the directory you stored the project in and double-click on projectname.xcodeproj. Here, I named the project Sprite, so I will double-click on Sprite.xcodeproj:Once it is open, you should see the interface as follows:

How it works…

Click on the play button in the upper-left corner to run the project.

This will run and show the default project running on the simulator. Congrats! You have Cocos2d running successfully.

The 2D coordinate system

In case of 2D game development, we just have two coordinate systems to worry about. The first is the screen coordinate system, and the other is the object coordinate system.

In 2D, whenever we place an object on screen, we always think as to how far the object is from the lower-left part of the screen. This is because the lower-left part of the screen is the origin and not the center of the screen. That is why if you place a sprite without changing its position, it will be created in the lower-left part of the screen. The screen origin, or the (0,0) position, is in the lower-left part of the screen. If you want to place the sprite at the center of the screen, you need to set the position to half the width and the height of the position property. As everything is with respect to the lower-left part of the screen, this is called the screen coordinate system.

The object coordinate system refers to the sprite itself. The center of the sprite is at the center of the object, unlike the screen, which has its origin in the lower-left part. The center of the sprite is called the anchor point. When you rotate a sprite, it will rotate about its center because its origin is at its center. You can change the origin of the sprite by accessing the anchor point property of the sprite.