However, that doesn’t mean the community couldn’t make a custom rom, but it’ll take a lot of work. Google aren’t releasing the Honeycomb source (instead we’ll have to wait for Ice Cream), additionally the community will need to integrate the drivers manually from NVIDIA.

While I’m sure we’ll see Honeycomb on the platform, I doubt it’ll ever be a nice slick implementation that you would get from an OEM-based rom. To be frank, if you want Honeycomb, best start saving the pennies for one of the latest generation of Android tablets. The Asus Transformer looks especially tasty. Personally I’m waiting for the quad core Tegra and Ice Cream, Froyo is enough for me for the moment.

At some point you’re going to hard lock your tablet, at least if you’re like me. Only problem is there’s no physical power switch and you can’t take the battery out. Have no fear! Press and hold the Power and Back buttons simultaneously, after a while the tablet will turn off. Press the power button again to turn it back on, and now you’ve got your tablet back to working order!

Update: This code is using an outdated version of the Cocos2D port. It’ll still work if you use the sample download linked at the end – but it’s using outdated API calls. Unfortunately I don’t have time to update the tutorial to the new release of Cocos2D. Sorry guys 🙁

Cocos2D is a fantastic library / game engine for numerous platforms from PCs to smart phones. It supports the vast majority of the features necessary to make almost any 2D-based game, it even includes a fully-featured physics engine!

As part of learning Cocos2D for Android I followed Ray Wenderlich’s tutorials for the iPhone port of Cocos2D. Of course we’re dealing with Android here, so here is his tutorial recreated for Android. Ray deserves all credit for this tutorial – the tutorial is originally his, this is merely a port to Android. Credit should also go to Sketchydroide for his basic template for Cocos2D on Android.

Downloading and Installing Cocos2D

I’m going to assume you’ve already got the Android SDK installed, along with Eclipse. If not, you can follow the guides at Google. You’ll also need to test with a real device, the emulator is far too slow to test Cocos2D applications, even one as simple as this tutorial. I’m also going to assume you know Java, otherwise you’re going to get lost very quickly. There are plenty of Java tutorials out there, don’t worry we’ll wait here while you learn. The basics of Android (such as what Activities are, etc.) are helpful to know, but not critical.

First you need to download cocos2d-android-1. I’m going to assume you’re using the pre-compiled library (the .jar), although you’re welcome to include the full source code if you wish. In fact when you’re developing on your own, the source code is a better option since you gain full documentation along with the ability to tweak the code should you need to.

Open up Eclipse and create a new Android Project:

Now you need to copy the cocos2d-android.jar file into the ‘libs’ folder of your project. If the folder doesn’t exist, create it.

Next download fps_images.png and put into the assets folder of your project. You are now setup with Cocos2D!

Initial Setup

Next you need to put some code into your default activity (SimpleGame) so that you can start making your game. At the top of the class add a protected field:

protected CCGLSurfaceView _glSurfaceView;

At this point Eclipse may be moaning about the line you’ve just added. This is because you haven’t imported the namespace. The easiest way to do this is to press CTRL+SHIFT+O. Any time you use a new class, try pressing this key combination any time a completed line has an error to do with missing identifiers. Next replace the onCreate method with the following:

This is the initial setup for Cocos2D. First we tell Cocos2D which surface to render to (the OpenGL surface we set up earlier). We then ask Cocos2D to display the FPS and to run at 60fps. Note that the 60fps is our animation interval, not the framerate of the application itself which is often limited by the device.

These notify Cocos2D with what’s going on with the device – such as when the user has switched to another application or the game is being stopped by the OS.

This is all the setup we really need. You can run the game now, but it won’t display anything at this early stage (we haven’t even set up a hello world scene!).

Adding a Sprite

Sprites are small images in 2D games that move about. These can be characters, projectiles or even clouds. In this game we’ll have three separate types of sprite: Player, target (enemy), and projectile. First we need a graphic to use! You can either create your own, or use the tasty graphics provided by Ray Wenderlich’s wife: Player, Projectile, Target. Place your sprite graphics within the ‘assets’ folder of your project.

Now we need to place the sprite on the game screen. Cocos2D has an inverted coordinate system to what you’re used to – the origin is the bottom left of the screen. So as X increases you head to the right of the screen. As Y increases you go up the screen. Additionally by default the origin / anchor point of sprites is in the centre. The coordinate system is the same regardless of the platform you run Cocos2D on. The following graphic should help you visualise the coordinate system of Cocos2D:

Enough boring theory, let’s get some code down! Add a new class to your project, call it ‘GameLayer’ and make it extend ‘CCLayer’. Add the following static method at the top of the class declaration:

Now when you run the application you should have a nice white background.

Moving Targets

While it’s cool to display a single ninja, because well, ninjas are cool – we don’t yet have much of a game. What we really need are some targets for our ninja to throw stars at. While we’re at it we might as well make them move to give them a fighting chance. What we’ll do is create the targets off the screen to the right, then have them move to the left of the screen at varying speeds. Add the following method after the constructor:

The code is rather verbose to make it as easy to read & understand as possible. Near the bottom we’ve introduced a new concept: Actions. Actions are a very accessible way of getting sprites to do things without constant babysitting. You can get sprites to move, rotate, fade, jump, etc. We use three different actions in this method:

CCMoveTo: The CCMoveTo action moves a sprite from its current position to a new one. In this case we’re moving the sprite from just beyond the right edge of the screen to just beyond the left edge of the screen (remember the origin of a sprite is the centre, hence why we divide the width by two). The duration is specified in seconds between 2 and 4. As an exercise, try changing the type from int to float so we aren’t restricted to whole seconds.

CCCallFuncN: The CCCallFuncN action allows you to specify a callback. The ‘N’ means this action allows you to specify a parameter.

CCSequence: This is a rather special action in that it doesn’t do anything itself. Instead it lets you run a sequence of actions, one after the other in a linear fashion. We use this so that we can move the sprite, then when the movement has finished call our callback.

The eagle-eyed may have noticed that we have a callback, yet the method doesn’t yet exist! We better correct that right now, add the following method to our class:

This method will remove the sprite when it has finished animating to the left of the screen. The second parameter is to ‘cleanup’ the sprite, this means it is completely unloaded and we get the memory back. In a real game you would only clean up a sprite as a last resort, re-using a sprite is much better from a performance perspective. We’re going down the wasteful route to make the concept of the game as simple as possible – simple is good when learning!

Now we have code to create and animate targets, but we never call this code! What we’ll do is spawn a new target every second automatically giving the ninja plenty of shuriken practice. Add the following line of code to the bottom of the constructor:

this.schedule("gameLogic", 1.0f);

Also add the following new method to the class:

public void gameLogic(float dt)
{
addTarget();
}

Now run the application and we should have some action:

Shooting Projectiles

I like to be able to shoot my targets, so let’s add some shooting! We’re going make things simple by having the user tap to shoot, where you tap is where the projectile goes.

We’ll use CCMoveTo to animate the projectile just like how we animated the targets. The problem is, CCMoveTo requires a destination to move to, but we can’t use the tap location since that means the projectile would stop in the middle of the screen. What we need to do is use the tap as a direction, rather than a destination.

This should look familiar to anyone who didn’t fall asleep in maths class – Pythagoras! Now before we fall asleep with yet more theory, let’s start coding. In the constructor add the following line:

What we are doing here is first enabling touch support. We’re telling Cocos2D that we are ready to handle touches for the current layer. Next we add code to handle touches from the user.

First we get the coordinates of the touch itself, and convert to the Cocos2D coordinate system. This method should work regardless of the orientation of the device.

Next we create the sprite and position it over the ninja. We then work out where the projectile should move to by extending the tap off the screen. This is done by getting the X and Y offset of the tap to the projectile’s starting position. We then get the ratio of Y to X, and simply scale the touch Y coordinate to match the scaled up X coordinate (which is just off the screen). The only problem with a simple algorithm like this is that the projectile must reach the right edge of the screen before it’s cleaned up, the projectile could leave the screen (top or bottom) long before it hits the right edge. There are solutions to this problem, but they’re beyond the scope of this tutorial.

After working out the destination, we need to work out the duration of the movement – we can’t have projectiles taking different amounts of time just because of the angle they’re shot at. To solve this problem we use Pythagoras to work out the distance the projectile needs to travel, then divide that by the velocity we want. This is because velocity = distance over time, or by re-arranging: time = distance over velocity.

Finally we run the actions on the projectile. Run the application and you should be able to start shooting shurikens!

Collision Detection

It’s no good if you can shoot shurikens, but they don’t actually do anything! To solve this problem we need to add some collision detection. To keep things simple we’ll use simple bounding box collision detection rather than the other more exotic methods Cocos2D provides.

To be able to run collision detection we need to be able to keep track of all of the sprites we have. Add the following fields to the top of the class declaration:

If you run the project now you shouldn’t notice any difference – but now we’re tracking all of our sprites! This gives us a great deal of extra power, and we shall use this power to add some collision detection. Add the following method to the class:

This is a brute-force approach to collision detection. Basically we iterate through all of the projectiles and targets, creating a rectangle for each and then checking if they intersect. If there is an intersection we remove the sprites from the scene and arrays. We use the ‘toDelete’ arrays since we can’t manipulate an array while we’re iterating through it in the manner we’ve chosen. Before the collision detection will work, we need to schedule the method to be called every frame. Add the following line at the bottom of the constructor:

this.schedule("update");

Finishing Touches

We’re pretty close to a fully working game now (albeit a simple one!). All games have sound effects of some sort, and this one is no exception! First we should talk about the audio formats Android supports, since Cocos2D can’t do anything about the supported audio formats on the platform it’s running on. The current port of Cocos2D on Android doesn’t contain a full sound engine yet, certainly not on par with CocosDenshion offered on the iPhone. For this reason we’ll use basic wav files for this tutorial. We’ll also add some additional code logic so you can win/lose.

First you’ll need to get some audio for the background music and a sound effect for the shurikens. You can source your own, or download the wav version of the background music, and pew pew sound effect from Ray Wenderlich’s tutorial. Put the wav files in the res/raw folder of your project.

In the constructor add the following code after the addChild(player) line:

Gimme The Code!

Where To Now?

This project provides a good basis for further development. Some possible changes were mentioned as part of the tutorial, others are limited only by your imagination! Check out the test projects that come with the source of Cocos2D, see if you can integrate some of them into the project here.

Eclipse is a very good IDE, I hesitate to say ‘excellent’ because it does have its drawbacks. For example it constantly gets in a muddle with dependencies when you deal with plugins. It’s also developed in Java, so it’s not the fastest IDE in the world. Still, it does offer the most important functionality necessary for fast development of Android applications. Of course being a programmer means I’m notoriously fickle about my development environment – all IDEs should follow Visual Studio and that includes Eclipse. First on the agenda is code hinting, Visual Studio provides this instantly and so should Eclipse!

To bring up the handy dropdowns instantly, go to Window > Preferences. Then go to Java > Editor > Content Assist. Set the Auto activation delay to 0. Of course you’ll need a fast PC, but I’m sure you do.

Next up is the colour scheme, I have my own (which is the correct one) and many other programmers have their own (which are incorrect). Fortunately Eclipse Color Themes have your back. Install their plugin, then download the theme that most closely matches your ideal colour scheme. A minor tweak later and you should get a good match to what you’re used to:

Lastly you’ll probably want to change the code formatting. What do you mean it’s fine as it is? OK OK, I was taught a specific code formatting style and to be frank while it’s not necessarily ‘standard’ in Java, it is very clear. I prefer code to be as clear as possible, giving bugs fewer places to hide. Fortunately Eclipse has the most advanced code formatting customisation I’ve ever seen. First up is the code style:

This lets you set up some basic prefixes / suffixes along with a few other style tweaks. The best part though, is the formatter:

This really lets you customise the code formatting, ensuring all code is formatted in the correct manner – my manner. The customisation is extremely extensive, and it’ll probably take you a while to make it format in exactly the manner you desire. Once you’re happy you can open up any source file and press CTRL + Shift + F to reformat the code, it’s extremely effective.

So that’s it for this little guide. There’s a lot to explore in the Eclipse preferences, and it’s well worth taking the time out to see just what’s available.