Cocos2d Game Development Blueprints
By Jordán Jorge
()
About this ebook
- Enhance your game development skills by building different types of iOS games in Cocos2d
- Create games of many different genres using the powerful features of the Cocos2d framework
- A step-by-step guide with techniques to discover the potential of Cocos2d Game Engine with interesting projects
Whether you are a passionate gamer, like developing, or are just curious about game development, this book is for you. The book has been written to teach 2D game development to app developers and to teach Objective-C to game developers, as learning Cocos2d is the perfect step for both roles.
Related to Cocos2d Game Development Blueprints
Related ebooks
Learning Libgdx Game Development Rating: 0 out of 5 stars0 ratingsAndroid Game Programming by Example Rating: 0 out of 5 stars0 ratingsCreating Games with cocos2d for iPhone 2 Rating: 0 out of 5 stars0 ratingsLearning Cocos2d-JS Game Development Rating: 0 out of 5 stars0 ratingsCocos2d-x Game Development Blueprints Rating: 0 out of 5 stars0 ratingsUnity 5.x By Example Rating: 0 out of 5 stars0 ratingsMastering LibGDX Game Development Rating: 0 out of 5 stars0 ratingsLearning Cocos2d-x Game Development Rating: 0 out of 5 stars0 ratingsHTML5 Game Development with GameMaker Rating: 0 out of 5 stars0 ratingsLearning LibGDX Game Development - Second Edition Rating: 0 out of 5 stars0 ratingsUDK iOS Game Development Beginner’s Guide Rating: 0 out of 5 stars0 ratingsMastering Android Game Development Rating: 0 out of 5 stars0 ratingsProcedural Content Generation for Unity Game Development Rating: 0 out of 5 stars0 ratingsGameSalad Essentials Rating: 0 out of 5 stars0 ratingsGetting Started with SpriteKit Rating: 0 out of 5 stars0 ratingsLibGDX Game Development By Example Rating: 0 out of 5 stars0 ratingsMonoGame Mastery: Build a Multi-Platform 2D Game and Reusable Game Engine Rating: 0 out of 5 stars0 ratingsBuilding Android Games with Cocos2d-x Rating: 0 out of 5 stars0 ratingsMastering Unity Scripting Rating: 0 out of 5 stars0 ratingsMastering iOS Game Development Rating: 0 out of 5 stars0 ratingsBuilding your First Mobile Game using XNA 4.0 Rating: 0 out of 5 stars0 ratingsCRYENGINE Game Development Blueprints Rating: 0 out of 5 stars0 ratingsPython Game Programming By Example Rating: 1 out of 5 stars1/5iOS Game Development By Example Rating: 0 out of 5 stars0 ratingsMobile Game Design Essentials Rating: 0 out of 5 stars0 ratingsMastering Unity 5.x Rating: 0 out of 5 stars0 ratingsLearning Android Game Development Rating: 0 out of 5 stars0 ratingsGame Development with GameMaker Studio 2: Make Your Own Games with GameMaker Language Rating: 0 out of 5 stars0 ratingsLÖVE for Lua Game Programming Rating: 5 out of 5 stars5/5Building Levels in Unity Rating: 0 out of 5 stars0 ratings
Software Development & Engineering For You
Adobe Illustrator CC For Dummies Rating: 5 out of 5 stars5/5Agile Practice Guide Rating: 4 out of 5 stars4/5Python For Dummies Rating: 4 out of 5 stars4/5Level Up! The Guide to Great Video Game Design Rating: 4 out of 5 stars4/5How to Write Effective Emails at Work Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5How Do I Do That In InDesign? Rating: 5 out of 5 stars5/5Modern C++ for Absolute Beginners: A Friendly Introduction to C++ Programming Language and C++11 to C++20 Standards Rating: 0 out of 5 stars0 ratingsGrokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Hand Lettering on the iPad with Procreate: Ideas and Lessons for Modern and Vintage Lettering Rating: 4 out of 5 stars4/5Tiny Python Projects: Learn coding and testing with puzzles and games Rating: 5 out of 5 stars5/5Lua Game Development Cookbook Rating: 0 out of 5 stars0 ratingsGood Code, Bad Code: Think like a software engineer Rating: 5 out of 5 stars5/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Beginning Programming For Dummies Rating: 4 out of 5 stars4/5Git Essentials Rating: 4 out of 5 stars4/5Photoshop For Beginners: Learn Adobe Photoshop cs5 Basics With Tutorials Rating: 0 out of 5 stars0 ratingsHow Do I Do That in Photoshop?: The Quickest Ways to Do the Things You Want to Do, Right Now! Rating: 4 out of 5 stars4/5OneNote: The Ultimate Guide on How to Use Microsoft OneNote for Getting Things Done Rating: 1 out of 5 stars1/5Learning Python Rating: 5 out of 5 stars5/5Data Visualization: a successful design process Rating: 4 out of 5 stars4/5The Essential Persona Lifecycle: Your Guide to Building and Using Personas Rating: 4 out of 5 stars4/5SQL For Dummies Rating: 0 out of 5 stars0 ratingsCoding All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsAgile: What You Need to Know About Agile Project Management, the Kanban Process, Lean Thinking, and Scrum Rating: 5 out of 5 stars5/5Android App Development For Dummies Rating: 0 out of 5 stars0 ratings
Reviews for Cocos2d Game Development Blueprints
0 ratings0 reviews
Book preview
Cocos2d Game Development Blueprints - Jordán Jorge
Table of Contents
Cocos2d Game Development Blueprints
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
Cocos2d v3.0
Pure Objective-C
ARC
CCDirector
CCLayer
CCArray
OALSimpleAudio
CCAction
CCActionCallBlock
Sequences
Schedule update
Enabling touches
Accelerometer events
Physics
What this book covers
What you need for this book
Who this book is for
Conventions
1-star challenge – accurate collision detection
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Sprites, Sounds, and Collisions
Creating a new Cocos2d project
Run Xcode Run
Understanding the default project
CCNode
Your first game – RunYetiRun
Creating the CCScene class
Adding the first CCSprite class
Anchor points
Placing things in context
Time for CCAction
Actions under control
Throwing some snowballs
Rolling down the hill
Managing collisions
Adding labels
CCLabelTTF
Updating labels
Making some noise
OALSimpleAudio
Voice memos
Audacity
GarageBand
Audio resources
Playing audio files
Game over
1-star challenge – accurate collision detection
The solution
2-star challenge – having three lives
The solution
Summary
2. Explosions and UFOs
Handling the accelerometer input
Linking the CoreMotion framework
onEnter and onExit
Converting accelerometer input into movements
Calibrating the accelerometer
Implementing the parallax effect in Cocos2d
CCParallaxNode
Particle systems
CCParticleSystem
CCParticleSystem modes
CCParticleSystemModeGravity
CCParticleSystemModeRadius
Common properties
Particle Designer
Extending CCSprite
Shooting some lasers
When UFOs collide
2-star challenge – create explosions
The solution
The attack of the aliens
Drawing and coloring
Drawing the life bar
1-star challenge – collision detection between Dr. Fringe and the UFO
The solution
Summary
3. Your First Online Game
Getting started with our project
Initializing the game
Creating labels with CCLabelBMFont
Littera
CCActions in depth
Drag, drop, and scale
Game Center
Configuring Game Center in iTunes Connect
Configuring the game in Xcode
Checking Game Center's availability
Authenticating the player
Turn-based games
The first turn
Passing the turn
Receiving the turn
Fighting cards
Labels for life points
Match over
Viewing the status when it's not our turn
Summary
4. Beat All Your Enemies Up
Creating an iPad-only game
Image sizes and names
Developing virtual game controls
Moving the zombie
CCSpriteBatchNode
Texture atlases
Creating texture atlases with TexturePacker
Loading texture atlases with Cocos2d
Creating your first animation
3-star challenge – hitting the air
The solution
Creating the zombie class
Creating the human enemies class
Keeping the main character in view
Taking human decisions
Drawing a life bar
Detecting collisions with enemies
2-star challenge – enemies' life bar
Game over
Summary
5. Scenes at the Highest Level
Initializing the game
Developing a tutorial for our game
Storing data using NSUserDefault
Loading data from external files
Transitions
3-star challenge – create a map scene
Summary
6. Physics Behavior
Physics engines
Game physics in Cocos2d
Introducing Chipmunk
CCPhysicsNode
CCPhysicsBody
Creating your first physics
CCPhysicsShape
Creating sprites with physics
Defining shapes
PhysicsEditor
Defining shapes
Loading PhysicsEditor shapes in Xcode
Advanced collision detection with Chipmunk
CCPhysicsBody and CCPhysicsShape properties
CCPhysicsCollisionDelegate
Creating a snooker game with Chipmunk
Setting the snooker table
Configuring the snooker balls
Hitting the cue ball
Managing collisions between snooker bodies
Summary
7. Jump and Run
Initializing the game
Configuring a varied scene
Scrolling the background and blocks
Coding custom physics
Jumping over the platforms
Adding a menu to the game
2-star challenge – adding pinecones to the scene
The solution
1-star challenge – adding a score label
The solution
Summary
8. Defend the Tower
Initializing the game
Developing a pathfinding algorithm
Following the path
Predefining defensive positions
Placing defenses
Giving AI to the defenses
Sharing information between nodes
Loading waves of enemies
2-star challenge – adding explosions
3-star challenge – upgrading defenses
Summary
Index
Cocos2d Game Development Blueprints
Cocos2d Game Development Blueprints
Copyright © 2015 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: January 2015
Production reference: 1230115
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78398-788-7
www.packtpub.com
Cover image by Vanesa Domingo (<vanesadomingo@insaneplatypusgames.com>)
Credits
Author
Jorge Jordán
Reviewers
Saeed Afshari
Nader Eloshaiker
Mohsin Mahmood
Commissioning Editor
Ashwin Nair
Acquisition Editor
Richard Brookes-Bland
Content Development Editor
Sumeet Sawant
Technical Editor
Siddhi Rane
Copy Editors
Safis Editing
Ameesha Green
Project Coordinator
Judie Jose
Proofreaders
Ameesha Green
Steve Maguire
Jonathan Todd
Indexer
Mariammal Chettiyar
Graphics
Vanesa Domingo
Production Coordinator
Aparna Bhagat
Cover Work
Aparna Bhagat
About the Author
Jorge Jordán is an iOS indie developer who has been passionate about how things work since his childhood. This is the reason why he graduated in Computer Science and became a Java developer. After buying his first iPhone, he became deeply interested in its technology and spent his spare time learning how to develop apps for Apple smartphones.
Over time, he founded Insane Platypus Games (http://insaneplatypusgames.com/) where he tries to make his dreams and games come true. He is also a member of the tutorial team at http://www.raywenderlich.com/.
In his free time, he loves to play video games and bass guitar, and to watch TV series.
You can follow him on Twitter @jjordanarenas.
I would like to thank my girlfriend, Angélica, for being so patient and for her support while I was spending almost all of my spare time writing this book. Also, I would like to thank my family, especially my mom and my brother, for always believing in me; it is thanks to them that I am the person I am.
Thanks to Vane (<vanesadomingo@insaneplatypusgames.com>) for creating all the art for this book and designing those charismatic characters.
Also, thanks to all my friends: the canupis, Javi Sáez, the jiervos, Kike, Pedro, Guille, Carmelo, and more, for all the laughs and the good times we spent together.
Finally, I want to thank the reviewers of this book for making it better and the rest of the people at Packt Publishing for making it real.
About the Reviewers
Saeed Afshari is an independent game developer based in Luxembourg. He has published more than twenty titles on the iOS App Store and Google Play under the brand Neat Games, and is focused on developing mobile games for iOS and Android.
He is a member of the Games, Interaction and Novel Interface Technologies (IGNITE) research collective at the University of Luxembourg, working on natural and novel user interfaces and understanding how people interact with games, and how games should interact with people. His current research projects deal with interaction with mobile games, virtual reality head mounted displays, and behavior change through serious gaming. He is the game developer for the European Commission project LiveCity
which deals with long distance multiplayer gaming on multi-touch tables.
With over fifteen years of experience in game development and interactive media, he has built up skills in platforms including OpenGL, DirectX, Unity, Cocos2d-x, and also interaction design for natural user interfaces and virtual reality. He has invented an algorithm to track permanent magnets for use in mobile games, in particular in the form of a magnetic joystick. He is willing to consult and collaborate on creating games and interactive software targeted for education, entertainment, and social networks.
For more information about Saeed and Neat Games, you can contact <pr@neat-games.com>.
Nader Eloshaiker is an Electrical Engineer in Computer Systems. His first involvement with technology started during his secondary school years when he built and sold 8-bit audio digitizers connected to the parallel port of a Commodore Amiga 500.
He became deeply involved in the home upgrade consumer market, always finding employment relating to computers and electronics.
At the birth of web-hosted databases for retail websites, he worked with Mark Cavallo of AEON Graphics developing high-end e-commerce web applications. Since then, he has been involved in a number of creative and advanced web projects with Mark.
For most of his professional career, he has worked at one of the largest automotive manufacturers in the world, based in Australia, managing global engineering design data.
He was also employed at Swinburne University of Technology as an adjunct teaching fellow while working full time as an engineer. His subjects included: object-oriented software design, Java development, web development, server-side web development, and user interface design. He also taught and was the convener for a Masters subject in internet networking infrastructure.
He has an open source application hosted by GitHub entitled Teamcenter Engineering Admin View, used to manage system security and workflow configuration for Siemens data management software. He has also developed BigZip, a free Java-based Winzip equivalent with an intuitive user interface that is ahead of its time.
His current project is developing an original iPhone game with Mark Cavallo. The last 5 years have seen him develop a vast wealth of knowledge with Cocos2d and iOS. This is an exciting direction for Nader and one he will continue to expand upon with his new company, Rotate Gears (http://www.rotategears.com/).
I would like to personally thank my loving and incredibly smart wife, Hanaa, as well as my adorable 1-year old son, Zain, both of whom have been very patient with me while I spent a lot of time researching Cocos2d and Apple's API so that I could develop my game. I would like to also acknowledge Mark Cavallo, who is my partner at Rotate Gears. His expertise as an artist and intuitive knowledge of game design has injected some amazing creativity into the game. Finally, I would like to thank my beautiful 5-year old daughter, Raya, who has been the source of my inspiration to develop a game. I hope that when this game is released, I will be able to spend more time at home and watch her grow into a woman.
Mohsin Mahmood is an active programmer and passionate developer of iOS Cocos2d-based games. He participated in development of various game projects and some of them are highly successful. Apart from this, he also worked in iOS large-scale business applications. As a technology junkie, he loves to develop with top-notch technologies.
With several years of experience in game and business application development, he has build up skills in cross-platform technologies. Currently, he is performing his duties as a senior software engineer.
For more information about him, contact <cocosjunkie@gmail.com>.
I would like to express my special gratitude to Packt Publishing, as well as to Indrani Mitra who believed in me. Also, I would like to thank Judie Jose for her kind guidance and coordination.
I would also like to thank my wife, Samra, and my sister, who helped me a lot in finalizing this project within the time frame.
www.PacktPub.com
Support files, eBooks, discount offers, and more
For support files and downloads related to your book, please visit www.PacktPub.com.
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
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 Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Free access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Preface
I grew up playing video games; I remember my Amstrad CPC 128K as one amazing computer that brought to my home several of the games I played in the arcades and I feel lucky for being born at that time. Thanks to that, I've known titles that have passed into history and I've been a witness to the evolution of the video game industry; from the first handheld games to the iPhone 6 and iPad Air 2, passing through the first computers and video consoles to the current next-gen.
This hobby became a passion and I realized very early that I would like to learn to develop video games so I could understand how my preferred titles were built, and this is one of the things I want you to learn through this book. In fact, there are three important things that I would like you to have learned by the end of the book:
Love for games: I think that playing any kind of game is one of the most important things in this life. Playing games in a balanced way can make your brain faster; you can learn culture, make friends, laugh, or even live a different life; that's why we should not stop playing.
Love for development: When I was a child, I realized that I wanted to be a developer because I wanted to know how to build the things I used to play. Once I became a developer, I realized how many things you can build by yourself with just a keyboard, and I think that making your own game or your own app can be compared to writing a book or recording a film. At the end, it is the same thing; you are creating something from nothing. So that's why I think that there are three things people should do before dying: have a child, plant a tree, and develop a game.
Autonomy: I would like you to have learned all the tools you will need to develop whatever is in your mind and to understand how to solve the problems you will find during this process.
From time to time, we hear news about a new game that is breaking the market and turning people crazy in a few weeks, achieving thousands and thousands of downloads, hundreds of thousands of profits from its in-app purchases, or millions of dollars in revenue. What makes this game so addictive? This is the question that most of us mobile game developers ask ourselves and the answer is always similar: a good idea. That's why most of us keep trying daily to think of good ideas to be the pillars of our next game, but this idea never comes to mind.
If you think about it, these addictive games are based on simple things and most of them are based on previous games, but their developers have included some features that make us want to play over and over. That's why it's important to learn which techniques were used to develop successful games from the past and the present.
But to achieve this, it's important to be equipped with the most appropriate tools in order to focus on playability rather than squeezing our brains trying to figure out how to do what we want. Hence, we have developed the games included in this book using Cocos2d because it's based on Objective-C, a language that I'm sure most of you are familiar with.
Cocos2d v3.0
Cocos2d for iOS (http://www.cocos2d-iphone.org) is one of the most powerful and popular frameworks to develop 2D games with. Its popularity is due to its features: it's open source and 2D; has a wide and collaborative community; supports sprites, collisions, scenes, transitions, audio effects, actions, physics, and animations; and has a lot more features.
At the time of writing this book, the current version is Cocos2d v3.0, released a few months ago, so if you have previous experience with this framework, it is possible that you will find some differences and new features.
Pure Objective-C
The syntax has been improved so method names conform to conventions and the code is now better structured. Also, the C libraries have been removed so now we will use just the Core Foundation classes.
ARC
Previously, the new projects created in Cocos2d didn't use Automatic Reference Counting (ARC) by default, but you could enable ARC with a little refactoring process. Now you can forget all these headaches of retaining, releasing, and autoreleasing memory as v3 is ARC-only.
CCDirector
The former [CCDirector sharedDirector].winSize feature has been replaced by the new [CCDirector sharedDirector].viewSize feature.
CCLayer
CCNode has replaced CCLayer. Previously, CCLayer was used mainly to support for touch and accelerometer events but since every node inherits from CCResponder and has this ability, it's no longer needed. Now CCLayer can't be inherited to create new classes to represent scenes; instead of this class, you should use CCScene from now onward.
CCArray
In the first versions of Cocos2d, CCArray was used thanks to the speed it provided. However, this advantage is no longer the case and during Cocos2d v2, a lot of developers were recommending not to use this class to manage arrays. That's why it has been deprecated in this new version and is no longer available.
OALSimpleAudio
CocosDenshion's SimpleAudioEngine, an external class, previously supported sound and audio effects. From now, ObjectAL's OALSimpleAudio class has replaced SimpleAudioEngine. This new class is focused on doing what we need in a simple way, converting complex actions into easy tasks.
CCAction
Almost all the action classes have been renamed to something like CCActionNameAction; despite this, its syntax remains unaltered.
CCActionCallBlock
Good-bye CCCallBlock, hello CCActionCallBlock. Something similar to what happened to CCAction also happens to CCCallBlock; it has been renamed but its syntax remains unaltered.
Sequences
The former CCSequence class is now named CCActionSequence and the most important change in this case is that when passing the array of actions to the sequences, you don't have to pass a nil object as the last element.
Schedule update
In the previous version, you should execute scheduleUpdate in order to schedule the update method to be called every frame. This is not needed anymore; now you just need to implement the update method in the way you want to work.
Enabling touches
Touch handling is now performed by CCNode and therefore by its descendants. To enable it now, you will need to set userInteractionEnabled to TRUE and implement either touchBegan, touchMoved, touchEnded, or touchCancelled.
Accelerometer events
As with touches, to enable accelerometer events handling, you need to set userInteractionEnabled to TRUE and you will also need to add the Core Motion framework.
Physics
Unlike what happened in Cocos2d v2, physics are now based on Chipmunk. Previously, we had both Box2D and Chipmunk to implement physics, but now the only library will be Chipmunk.
What this book covers
In this book, you will find eight chapters, each covering a different genre of video games. The aim of the book is that you learn the features of Cocos2d at the same time as you discover the singularities of several games that have been or are currently successful in the video game industry.
Chapter 1, Sprites, Sounds, and Collisions, covers the first steps of developing with Cocos2d v3.0. This chapter will guide you through how to create a horizontal-scroll game in which you will create sprites from an image. You will also learn how to move sprites across the screen thanks to executing actions, and in case it's needed, how to manage collisions. Also, you will learn how to show score labels and how to play background music and sound effects. The best of all, this game will be available on both iPhone and iPad devices.
Chapter 2, Explosions and UFOs, shows the process of developing a classic shoot 'em up in which the accelerometer takes control of the movement. In this game, you will learn to load and set up particle systems such as explosions and fire and draw primitives (lines, circles, and squares) on a CCNode instance. In addition, you will be introduced to the parallax effect and you will implement it in the game.
Chapter 3, Your First Online Game, teaches you the development of a turn-based game with the particularity that it will allow you to play against another player thanks to the configuration of Game Center in your game. Also, you will learn how to drag, scale, and rotate sprites and how to include labels using bitmap fonts. As this is a turn-based game, you will learn to include timers to control each player's turn.
Chapter 4, Beat All Your Enemies Up, takes you back to the 80s and 90s as you learn to develop one of the classic arcade genres: the beat 'em up. In this chapter, you will learn to create an iPad-only game in which players will move thanks to a track pad you will develop. As this kind of game demands that the characters perform different movements, you will learn to animate the sprites using several image files to optimize sprites' management. You will also will learn how to use sprite sheets.
Chapter 5, Scenes at the Highest Level, covers the development of a brain game in which you will create a tutorial so players can learn the basics of the game. You will learn how to load data from external files to configure the different scenes and how to create transitions between these scenes. In order to keep the user's data, you will learn how to save this information.
Chapter 6, Physics Behavior, introduces you to the physics world but the high-level one because you will learn to take advantage of Chipmunk, a physics engine available in Cocos2d. You will learn to set up and run a Chipmunk simulation and to create and reuse bodies. Collisions are managed by this library too, so you will learn how to use collision filters and listeners to create a sports game.
Chapter 7, Jump and Run, creates a platform game that will handle specific collision logic and manage multiple touches. Also, you will learn how to use multiple sprites to texture varied terrain and you will learn how to add a menu to the game so players can configure some setups.
Chapter 8, Defend the Tower, teaches you how to create a tower defense game and you will learn how to provide Artificial Intelligence to non-playable characters. In addition, you will develop a pathfinder algorithm so these NPCs know which path is best for them. Through this chapter, you will also learn to include notifications and in-app purchases.
What you need for this book
To develop this book's games, you will need the following hardware and software:
An Intel-based Mac running Mac OS X 10.8.4 or later
The latest Xcode version (5.1.1 at the time of writing this book)
To be enrolled in the iOS Developer Program if you want to test the games on a device and to use in-app purchases
An iOS device to test games on
You don't need wide development experience in either Objective-C or Cocos2d as these chapters guide you step by step so you understand what is happening. However, you do need to have an intermediate knowledge level of Cocos2d and an understanding of Objective-C.
Who this book is for
If you are a passionate gamer, you like developing, or you're just curious, this book is for you. It has been written to teach 2D game development to app creators and also to teach Objective-C to game developers. In both cases, you will find a common point: games. If you have developed several apps and now you want them to include gamification, or if you have been developing games using other frameworks and you want to take advantage of what Cocos2d offers, this book is for you.
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: A CCScene class is a class that inherits from CCNode and whose main purpose is to contain the behavior of a single scene in the game.
A block of code is set as follows:
// Create a colored background (Dark Grey)
CCNodeColor *background = [CCNodeColor nodeWithColor:[CCColor colorWithRed:0.2f green:0.2f blue:0.2f alpha:1.0f]];
[self addChild:background];
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: In the project navigator, select the Resources group, right-click and select Add Files to
RunYetiRun….
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Sometimes, you are going to be challenged by me requesting you to try to solve a particular situation. These challenges will be labeled as 1-star, 2-star, or 3-star challenges depending on the difficulty of the task, but they can be solved with the knowledge acquired throughout the book. They will look like this:
1-star challenge – accurate collision detection
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 <feedback@packtpub.com>, 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 from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. 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.
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/7887OS_ColoredImages.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 <copyright@packtpub.com> 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 <questions@packtpub.com>, and we will do our best to address the problem.
Chapter 1. Sprites, Sounds, and Collisions
In the first chapter of this book, I will introduce you to the basics of developing games, specifically how to do it with Cocos2d. I'm sure that most of you have heard technical terms such as sprites and collisions before but how many of you know how to create and work with them? Throughout this chapter, I will teach you enough to answer this question and I will guide you through building a horizontal scrolling game similar to Jetpack Joyride and Flappy Bird that will run on both iPhone and iPad.
In this chapter, we will look at the following:
How to create a Cocos2d game that will run on iPhone and iPad
How to enable touch detection
How to manage collisions
How to load images and sounds
How to play sound effects
How to create score labels and update them
Creating a new Cocos2d project
In this book, we work with the latest Xcode version (5.1.1 at the time of writing), Cocos2d v3.0.0, and iOS7.
If you are familiar with Xcode, creating a new project should be easy enough to do alone but I would like to explain what the project creation process looks like in Cocos2d v3.
First of all:
Create a new Cocos2d project in Xcode by selecting File | New | Project….
Click on the cocos2d v3.x template under iOS and you should see the two icons shown in the following screenshot:
Choose the cocos2d iOS template and click on Next.
Call it RunYetiRun and make sure Universal is chosen on the Device Family menu before clicking on Next.
Select the place where you want your project to be saved and click on Create.
I would like you to focus on the project navigator, the section on the left that contains the folders and files that will give life to our game:
This pane contains a hierarchy of files and folders in your Cocos2d project that does not reflect the real location of the files on your hard drive. In other words, the pane shows the files in your Xcode project and lets you organize these files in a way that is unique to Xcode.
Folders in the navigator are called groups and are used to organize the classes, images, and the rest of the files, but moving them will not affect their real