Cocos2D-Swift 3.0: A great way to get started developing iOS games!

If you’re new to iOS game development now is a great time to get started. In 2008 a brilliant engineer named Ricardo Quesada rewrote his 2D game engine for Apple’s iOS and released it as open source. It’s no exaggeration to say that hundreds of games, like my own, were developed using Cocos2D—including dozens of hits. Now it’s 2014 and the newbie game developer has several versions of Quesada’s Cocos2D framework to choose from. But for me the branch of Cocos2D devoted to the iPhone and iPad will always have a special place in my heart. Clearly Cocos2D-iPhone (now called Cocos2D-Swift) was the inspiration for Apple’s SpriteKit framework. And once you learn the fundamentals of Cocos2D on iOS you can easily transfer these skills to Android, Windows, and HTML5 versions of the Cocos2d family. Working with Cocos2d-Swift is like “reading Shakespeare in the original Klingon.”

Learning iPhone Game Development with Cocos2d 3.0 by Kirill Muzykov is a book I wish I had when I was learning to develop my first iPhone game. Muzykov patiently covers all the basics (nodes, sprites, actions, text, sound, buttons, menus) and jumps into advanced topics (particles, physics, tile maps, iTunesConnect, Game Center, and in-app purchases) while guiding the reader though creating a game called CocosHunt and using important tools (Particle Designer, Texture Packer, Tiled) and websites (freesound.org, media.io).

Along the way the reader also learns about Objective-C, Xcode, and iOS APIs. You’re still a beginner by the time you finish Muzykov’s book but you’re a well informed beginner and ready to tackle larger and more complex projects—like the next Candy Crush.

One of the best things I like about Muzykov’s book is it’s structure. A typical chapter starts with setting up a project and cycles through segments entitled “time for action” and “what just happened?”. This alternating rhythm becomes a reliable way to digest the material and ensure the author doesn’t wave his hands over new concepts. Almost every chapter includes a pop-quiz. I’m not a big fan of quizzes but if that’s what you need to re-enforce the material Muzykov provides them.

The source code is clean and clearly written with good comments. Muzykov keeps the syntax simple, using “typedef enum” instead of “typedef NS_ENUM” and “#define” instead of “FOUNDATION_EXPORT NSString *const” which is probably for portability. Much of a game is managing state and game developer who follow Muzykov examples in his classes won’t get into trouble.

If you’re new to mobile game development and you want to focus on iOS then Learning iPhone Game Development with Cocos2d 3.0 is a good book for you.

Re-doing Dungeonators

Meet the Dungeonators

One thing I think all software developers love to do is to make software for “the heck of it.” Hacking something together without having to worry about users, open source community members, and code reviews, is something devs don’t get to do often in these days of test-driven, agile, minimum viable products. Back in 2011 I created an iPhone game just for the heck of it. I wanted to learn about the indy game development process and there isn’t a better way of learning than by doing. I accomplished my mission and uploaded the first version of Dungeonators to Apple’s iTunes App Store in October of 2011. While the game is not very playable, I learned a lot:

  • How to design and implement a realtime game with Objective-C and the Cocos2d-iPhone framework
  • How to create all the art, fonts, sprites, and a spite atlas
  • How to record (or buy) all the sounds and music and use open source tools to transcode audio for a game
  • How to create the mechanics of a game with objects and callbacks while ref counting to manage memory
  • How to test and deploy an iOS game and get something approved in the App Store

Now it’s 2014 and much has changed in the world of indy game development for iOS. Apple’s iOS 7 introduced Sprite Kit which reduces the need for a framework like Cocos2d. Apple also introduced the iPhone 5 and the iPad with Retina, which mean there are four iOS screen resolutions/aspect ratios in common use. Oh, and let’s not forget Flappy Bird and 2048. While writing a hit indy game is still harder than winning the lottery it looks like a couple of people have done it!

Since I’m taking a break between adventures, I thought it would be fun to update Dungeonators for iOS 7 and Sprite Kit. Plus it would be good to make the game universal (available on all iOS devices) and global (available in more than just the United States edition of the App Store). And I should probably make it playable!

The technical part of this plan is relatively easy. iOS 7 is easier to develop with than previous versions of iOS. I can use ARC (automatic reference counting)in addition to manual ref counting. All the music and sound effects should just work fine. My custom Objective-C classes just need some simplifying (I wrote too much code–that’s my bad coding habit). The original Dungeonator’s artwork is all vector-based so rendering it in different resolutions for each iOS device shouldn’t be too hard. Finally, Sprite Kit is remarkably similar to Cocos2d. Porting the scenes, sprites, transitions, and actions will also be easy.

D2-2014_2
High resolution Dungeonators under development (1136 x 640 pixel rendering)

The hard part is creating a playable game. If you download original version of Dungeonators from the App Store you’ll find it really confusing. How do you play? Where to you touch? What is the goal? I don’t know what I was thinking!

Actually I do know what I was thinking. I was thinking about the inside not the outside. Inside there are classes for characters, strategies, spells, payloads, and matches. Way too much to fit in a casual game. So while I’m porting everything over I’m going to tear out hundreds of lines of code. I’m going to simplify Dungeonators to the point where it doesn’t require a personal demo from me to learn how to play!

I still might not have a playable game but at least it won’t crash anymore!

ARC Memory Management in iOS 5 and Cocos2d-iPhone 2.0

My rewrite of Dungeonators is crawling along at a glacial pace. Mostly because I can only work a couple of hours a week on the project. But the iOS 5 way to manage memory with ARC (automated reference counting) is making the process far less painful than it was the first time I wrote my game. ARC uses annotations and some new key words to manage memory on your behalf. It works very well if you’re doing simple client-side game development and don’t have to worry about backward compatibility with iOS 4.

Here is an example of how ARC changes your life for the better…

In the old days you would declare out your ivars, declare your properties, then synthesize and map them together, and release them in a dealloc method. This little design pattern required 4 repetitive lines of code for every ivar (instance variable) and engendered flamewars about  coding style and where underscore should go (if you thought it was necessary to distinguish an ivar name from a property name).

Pre-ARC Entity.h

Pre-ARC Entity.m

In this new modern era of automated reference counting I just declare properties, I don’t worry about accessing the ivars directly, and I don’t write my own dealloc. It’s a lot less code in a complex game where characters and objects have dozens of properties.

Post-ARC Entity.h

Post-ARC Entity.m

To get Cocos2d-iPhone to work with ARC was really easy: I just replace the NSAutoreleasePool object in main.m with the new ARC friendly @autoreleasepool annotation. (I might not have had to do this but it’s supposedly more efficient.)

The downside, as I stated above, is that your app will only run on iPhones, iPads, and iPods running iOS 5 and you need to use Cocos2d-iPhone 2.0. But I think that’s a fair tradeoff. Backward compatibility is a killer of the artistic soul and should be avoided where possible. To Err is human, but to upgrade is divine 🙂

Check out Ray Wenderlich’s excellent ARC tutorial for all the gritty details!

Dungeonators Battle UI Redesign


There is nothing quite like real user feedback. The Dungeonators game that I started coding about a year ago has been through several design iterations. Before I wrote a line of code I mocked up the whole UI and tested that on my friends and kids (paper prototype, an honorable UI design tradition). And with each development build I tested everything again and even enlisted strangers. I must have played though the final release candidate a 100 times. (It was then that I realized that game programmers must get sick of their games if they properly test them!)

When I uploaded Dungeonators to the App Store on 14 October 2011 I was pretty confident about the game play and the user interface. Famous last words as they say 🙂

After an initial healthily growth curve Dungeonators installs tanked:


The message I get from this user adoption curve was simple: Dunegonators stinks!

So I went back to the drawing board to search for the stinky bits. After much reflection I realized three things:

  1. Dungeonators is too hard for casual users and too easy/dumb for hardcore gamers. People who play MMORPGs like World of Warcraft punch through my game. People who play Angry Birds get stuck around level 1.6. (Which is as far as you can go if you don’t know what you’re doing.)
  2. People don’t know what to touch. They want to touch the avatars and not the raid and spell frames. If you don’t know what raid frames and spell frames are then you are not going to get my game.
  3. I was going to have to fix this. I could fix this problem with a lengthy tutorial or FAQs. But Dungeonators is causal game not productivity software. I never read manuals and skip tutorials. I expect my audience to have the same level of self respect!
So here is the new battle UI that tries to clean this mess up:
  • The good guy raid frames (on the left) are no longer touchable: They just display status. I couldn’t find a casual user who knew what a raid frame was so I got rid of raid frames.
  • Good guy spell frames are no longer associated with good guy raid frames: Spell frames are now modeless and never hidden. Each good guy has two spells available 24/7. As the game progress the spell are automatically upgraded. I’ll have to rewrite the game mechanics to handle the fact that the total number of available spells has gone from 4 x 6 (which I understand is 24) to a mere 8. But that actually makes Dungeonators a heck of lot simpler to program and to play.
  • The bad guy raid frames are still touchable and still enable the player to switch targets. But in the original UI you could have separate bad guy targets for every good guy. In the revised UI all the Dungeonators are synchronized. It’s a gross simplification that is all for the best.
  • Touching the center of the screen, where the avatars live, is still not part of the game play but if you do, the game will pause and bring up the main menu. I was able to kill two birds with one stone: No main menu button and a valid response to a user touch. Feedback is everything thing: In the original design touching the center of the screen was ignored and could have been interpreted as the game freezing up.
In general I learned what I thought I always knew: iPhone games have to be simple and causal gamers don’t have the time or energy for complex mechanics. But in practice I learned a lesson that every battled hardened game developer must know after their first game is released: There is no better test case than the real world!

Sprite Playground

I wrote a little Cocos2d-iPhone test app and committed the project to GitHub. (Like every dutiful hacker should.) You’re welcome to download the project and fool around with the code.

My goal was to figure out how to create a composite sprite, make sure it could respond to touches, and rotate and move it round the screen. With a little trial and error I got it working. Here’s how I did the hard parts:

I created a sprite from an PNG file and got it’s dimensions:

Then I created a CCNode to be the parent of my sprite sandwich. (I originally tried to use my cocos2dGuy CCSprite as the parent but Cocos2d stacks added on top of partent nodes and I wanted the particle effect under the cocos2dGuy not on top of him.) I set the size of the CCNode to the dimensions of the cocos2dGuy so that when you touch the CCNode it responds as if you’re touching the image. Then I add the CCNode to the layer. It’s also important to set the CCNode’s anchorPoint to the center (0.5, 0.5) as it’s default is bottom-left. CCSprite default to center anchorPoints and I want my CCNode to act like a proper sprite.

Next I added the cocos2dGuy sprite to the center of the composite CCNode. These two entities are now both the same size and stacked on top of each other. (It’s probably not necessary for me to set the cocos2dGuy’s anchorPoint and so I’ll remove that line of code down the road.)

Finally I created the custom CCParticleSystem from a Particle Designer file and added it to the composite CCNode but at a lower Z value show it shows up under the cocos2dGuy sprite. See how I had to set the position and the anchorPoint to ensure everything lined up.

Movement and animation are easy in the world of Cocos2d. I really like the visual effect of CCEaseExponentialInOut. It has a nice punch.

Handling touches are bit harder. I had to remember to set self.isTouchEnabled = YES in my init method and override both registerWithTouchDispatcher and ccTouchBegan. The key bit of code for responding to a touch is isTouchForMe:

The main thing here is to give each touchable node a unique tag and test each node in the layer for that tag. If you touch the sprite he inflates for a moment. If you touch an empty part of the screen the sprite turns and launches himself at your finger. Ouch!

Cocos2d-iPhone Sprite Rotation to an Arbitrary Point

I had some time during the Thanksgiving weekend to work on Dungeonators. I’m hoping to get an upgrade out to the App Store soon. One thing I needed //TODO: is refactor my rather poor implementation of rotating a sprite to face another sprite. My original code worked ok, in a roundabout way, but was ugly and mysterious.

(My iPhone game is full of ugly mysterious code: As I implement my ideas in code I first focus on getting it to work. Then, if I have time I go back and fix it to work cleanly. Generally cleanly means boiling the code down to the fewest number of lines possible, making it as functional as possible, and using functions from the operating system or open source code libraries as much as possible.)

I won’t show you my original sprite rotation implementation. Some things are too gross even for the Internet. Let’s just say it was written as if I was trying to remember high school trigonometry by trial and error.

Instead below is the final implementation, useful to any Cocos2d-iPhone programmer who wants a sprite to rotate to face an opponent at any point on the screen:

And here’s how it works, just incase you’re curious…

  • The method takes a source sprite and as target sprite as parameters. After it runs it will rotate the source to face the target.
  • The calculation part uses Cocos2d helper functions and macros (ccpSub, ccpToAngle, and CC_RADIANS_DEGREES) to figure the maths. In my original implementation I had written my own versions. Using the Cocos2d API makes my code easier to read and perhaps faster.
  • The maths work like this: Create a vector out of the distance between to points. Convert the vector to an angle. Convert the angle from radians to degrees and negate it*. Add 90 degrees to the angle to get the proper orientation. (The +=90.0f value is game specific: My sprites are rotated 90 degrees to start with.) Subtract the penultimate result of the calculation from the current rotation property (angle) of the source sprite to get the final result (the amount to rotate by).
  • The animation, which could easily be factored out into a method of its own, uses Cocos2d’s CCRotateBy and CCEaseIn to turn the source sprite to face the target in half a second. This part didn’t change from the original code. I didn’t factor it out because in my game I always use these two pieces together. I don’t like to do too much work in the abstract because I usually end up making my code too complex.

* The need to negate the value produced by CC_RADIANS_DEGREES is a bit of a mystery to me. If I don’t do it my sprite ends up facing in the opposite direction.

Dungeonators iPhone Game Released in the App Store!

Writing a real game, from scratch, in Objective-C, with original Art and sound effects, took a heck of a lot longer than I imagined. Even with the help of the Cocos2d-iPhone framework!

You can find it here: http://bit.ly/rkZvCJ

Here’s what the sprite atlas looks like (formatted by Zwoptex) …

And here are some stats:

Now you know all my secrets!

 

 

Invalid Code Signing Entitlements

Finally after 11 months I submitted my iPhone game, Dungeonators, to iTunes Connect for inclusion in the Apple App Store. I’m planning on giving it away so the “warcraft meets angry birds” funs is accessible to everyone! I hope it passes Apple’s review process 🙂

It took several attempts for me to get to “waiting for review status”. Here are the step I went through in hope that if you, in the near future, need to submit an app for the first time, you can succeed on your first attempt.

At this point set a cold beer within easy reach…

  1. Most of the info from Apple and the books on iPhone development is based on the old Xcode 3-based application submission process. Google Xcode 4 iTunes connect for the most recent tips. I’m not even going to include a link because the info goes stale fast. Just google it.
  2. Set your app’s pricing and metadata in iTunes connect. You’ll need a 512 x 512 icon too.
  3. Follow all the directions about distribution certificates and distribution provisioning profiles. Like a double-linked list your distro cert should point to your provisioning prof and vice versa.
  4. First create the distro cert via keychain access app on your map. Make sure there is key associated with your distro cert after you install it in your key chain.
  5. Second create your distro provisioning prof and install it in Xcode 4. Make sure your target’s code signing entitlements point to your distro provisioning profile for the release build.
  6. Clean and Archive your app with the Product menu in Xcode 4. The Archive scheme should be set to your release configuration.
  7. In the Organizer window validate and submit your app. You’ll need your iTunes Connect password.
  8. If you get the dreaded “invalid coding signing entitlements” don’t panic. It could mean a lot of different things. But if your iOS app is simple then it’s most likely  the iCloud entitlement. (Google it for more info.)
  9. Go to App IDs in the provisioning portal. Scroll to the bottom. Click configure on the row that represents your app’s ID. Uncheck Enable for iCloud. Click Done. Create a new distro provisioning prof and reinstall it into Xcode 4. Go to iTunes Connect and reject your binary. Go back to Xcode’s Organizer window and do Validate and Submit again.
  10. If you get an invalid binary. Drink a beer and try again! (do while beer != empty)
See, that was easy!

Hey It’s Easier Than You Think (Xcode 4 and Subversion)

I love how the new Xcode 4 shows you code changes side-by-side with it’s version editor view. But I had a little problem. I’m a subversion fan. Yes, I know, totally not cool. I keep this flaw a secret and I don’t force my preference on my co-workers nor do I tweet about it. I’m sure with years of therapy and the love and support of my family I’ll get over it.

But in the meantime I’m working on an iPhone game and I have a free subversion repository from my ISP. I want to continue to use this fee repository even though Apple gently nudges you to GIT with Xcode 4.

I’m stubborn. I tried GIT and it’s not doing anything for me. My change control needs are small. The functionality that makes GIT great is way more than I need: I’m not working on a large team with a complex build system that has to commit changes with the finesse of a tightrope walker.

Today I went back to subversion and my free repository when I had to update my iPhone to the release candidate 3 of the Cocos2d framework (which is host on Github BTW). Back when Xcode 4 was release I just could get Subversion and Xcode to play nice. But being stubborn, I tried again and to my surprise succeeded.

I don’t think Apple changed much. I think I was just impatient and misinformed. There is a lot of silliness about how to set up Xcode 4 to work with a Subversion repository on the Internets. What worked for me is the functionality that Xcode gives you out-of-the-box (without using the terminal). It was point-and-click but just not automated.

If you’re interested here is how you get a hosted subversion repository to work with Xcode 4. Have fun and don’t sweat the snickers from your more version control evolved friends 🙂

  1. Create a new Subversion repository that you can access via your protocol of choice (mine is the open Internet and HTTP because that’s what Dreamhost provides). Leave this repository empty–we’ll use Xcode 4 to set up all the directories. Just remember your URL and password.
  2. Open Xcode 4 and go the Repository tab in the Organizer Window.  Click the tiny little plus sign in the lower left corner to add a connection to a Repository. Enter in the URL and password and wait for the little circle to turn green. Xcode 4 should automagically detect the type of repository. Be patient. This process takes a bit of time and there is absolutely no feedback: Apple forgot to spin the beach ball here.
  3. When you get the green circle click on the root directory icon on the left under the name of the repository and create 3 directories using the New Directory button on the bottom: trunk, branches, tags. Be patient again and wait for the directories to show up in the center pane of the Organizer window.
  4. Click on the name repository on the left and enter the names of our your 3 directories in the 3 fields provided. (See the genius of naming them trunk, branches, tags?) If your spelling is good you’ll get 3 more green circles.
  5. Click on the Trunk directory on the left and then click on the Import button on the bottom. Select the folder that contains the project you want to put under source code control. Now go away. Get a drink and watch an episode of South Park. You have to be patient because not only is there no beach ball, spinner, or progress bar, there is no green circle!
  6. When you come back you should see your imported directory listed on the main pane. If you click the arrow to the left of it you’ll find your Xcode 4 project file and a subdirectory of files. Remember to be patient. Your poor overworked laptop has to ask the Subversion server for all this info and it takes way longer than 200 milliseconds to get back to you.
  7. Make sure your original Xcode project is closed and hidden away for safe keeping. Click on the imported project in the main pane of the Organizer window and click on the Checkout button on the bottom. Select a location on your hard disk to store your working copy of the project that won’t conflict with the original project. It should be OK to overwrite the original but I’m just paranoid. (Years of experience will do that to you.)
  8. Get a cup of coffee and troll Reddit for some laughs. When you come back Xcode should ask you in a dialog box if you want to open the project that you just checked out. Say yes and run it just to be sure it’s all there. (Paranoia again, sorry.)
  9. Now make a change to your and look for the little M to the right of the file name in the Project Navigator pane to show up. Be patient. If it’s not showing go back the the Organizer Window, back to your Project folder (by selecting its name on the left), and click the Commit button. The little M should now and forever show up next to your modified files in the Project Navigator.

I’m still having a little problem committing from the context menu in the Project Navigator but I can commit just fine from the Organizer Window. Maybe that’s just how Subversion works with Xcode or more maybe I have to be even more patient. I’ll let you know!

Cocos2d Tip#3: Making Your iPhone Game Fast

My first iPhone game, that might actually make it to the App Store, is just about done. (Not done done but almost ready for testing and tweaking.)

With the idea that other people beside me might actually play my game I’ve started to do a very dangerous and high risk activity: Optimization!

The all the famous Computer Scientists and Software Architects agree: Optimizing your program is a necessary evil, like the death penalty or bug tracking systems, and to be avoided at all costs.

Well, that’s not quite true. It’s premature optimization that is the bad guy here. Don’t start out programming with performance or scalability in mind, least you optimize code that doesn’t need it and miss optimizing code that really needs it. (It’s the same for bug tracking systems–don’t put all your junk in Jira or Bugzilla–just the verifiable, repeatable bugs that you might actually fix one day.)

When I started my game I knew my ideas were going to evolve and I didn’t want to hard code myself into a corner. I consciously wrote code that I knew would be slow but flexible.

For example I used expensive string comparisons instead of testing for cheap numeric constants. During the initial development phases of my game the strings were self-documenting (I could read them like little notes to myself) and easy to change. Later, when my game solidified and the string comparison were easy to find using Xcode’s Find in Project command (which is now Xcode 4’s Find in Workspace command)…

Changing the type of Character’s role property from NSString* to CharacterRole (a typedef’ed int) sped up my game in update methods which were called with every frame change. It was a pain to add all the constants but at least I only had to do it once–even though my conception of a Character and a role changed quite a bit.

Another big optimization I did was to replace for-loops and with Cocos2d’s fast enumeration macros…

My list of good guys changes during the game so I stored them in a CCArray–Cocos2d’s version of a NSMutuableArray. CCARRAY_FOREACH is a Cocos2d macro supercharged for fast array access. I could have used the Objective-C version of a fast numerator but I like to use as much of Cocos2d as I can. That way when I port my game to Cocos2d-x (C++ cross-platform version) it will be less work 🙂

One of the biggest optimizations I did was to upgrade from Cocos2d 0.99.5-rc1 to 1.0.0-rc. You have to be smart about when you upgrade to a new version of a framework. I don’t agree with the idea of living on the bleeding edge–stability of the platform allows me to focus on my own bugs!

Upgrading from Xcode 3 to Xcode 4 also seemed to help, or at least not hurt, performance. The new version of Cocos2d seems to work better with Xcode 4. I’m still getting used to the shiny new Xcode–it acts weird and slow on my Mac Mini.

To make framework and Xcode upgrades easy I put very little code into my app delegate class. All I have to do is to comment out…

and replace it with…

There are lots more optimization I can do if my performance isn’t where I want it to be: Unroll my loops and get rid of Character lists altogether. But I’ll lose a lot of abstraction and flexibility so I’m not going to optimize anything more unless my beta testers complain!