OTHER

This is a blog post by iOS Tutorial Team member Gustavo Ambrozio, a software engineer with over 20 years experience, including over three years of iOS experience. He is the founder of CodeCrop Software. You can also find him on Google+.

The squirrels are on a rampage!

This is the second part of a two part tutorial series where we’ll build a cool catapult type game from scratch using Cocos2D and Box2D!

Creating Targets

The targets creation won’t be anything very complicated as it’s mostly what you already know. Since we’re gonna have to add a bunch of targets let’s create a method to create one body and then we can call this method a bunch of times.

First let’s create a few variables to keep track of our new bodies. In the .h file add these variables:

The method has a lot of parameters because we’ll have different types of targets and different ways of adding them to the scene. But don’t worry, it’s pretty simple, let’s go over it bit by bit.

First we load the sprite using the file name we pass to the method. To make it easier to position the objects the position we pass to the method is the position of the bottom left corner of where we want the target. Since the position Box2d uses is the center position we have to use the sprite’s size to set the position of the body.

We then define the body’s fixture depending on the desired shape we want. It can be a circle (for the enemies mostly) or a rectangle. Again the size of the fixture is derived from the sprite’s size.

Then, if this is an enemy (enemies will “explode” later on and I want to keep track of them to know if the level is over) I add it to the enemies set and set the fixture userData to 1. The userData is usually set to a struct or a pointer to another object but in this case we just want to “tag” these fixtures as being enemies’ fixtures. Why we need this will become clear when I show you how to detect if an enemy should be destroyed.

We then create the body’s fixture and add it to an array of targets so we can keep track of them.

Now it’s time to call this method a bunch of times to make complete our scene. This is a very big method because I have to call the createTarget method for every object I want to add on the scene.

Here are the sprites we’ll be using on the scene:

Now all we have to do is place these at the right positions. I got these by trial and error, but you can just use these premade positions! :] Add the following method after createTarget:

Pretty simple stuff – just calls our helper method for each target we want to add. Now add this to that bottom of the resetGame method:

[self createTargets];

If you run the project now you won’t be able to see this part of the scene unless you throw a bullet at it. So just until we have the scene figured out, let’s add a line to the end of the init method to make it easier for us to check of the scene is as we envisioned:

self.position = CGPointMake(-480, 0);

This will show us the right half of the scene instead of the left half. Now run the project and you should see the scene of targets!

You can play a little with the scene before moving on to the next step if you want. For example, comment out the 2 bricks at the right of the first block and run the project again and see what happens.

Now remove the line that changes the position from the init method and run again. Now throw a bullet at the targets and watch the destruction!

Cool! The squirrel attack is underway!

Rapid Fire

Before we move on to do some collision detection let’s add some code to attach another bullet after we throw one just so we can make some more destruction.

On this method we first check to see if we destroyed all the enemies. This won’t happen now as we’re still not destroying the enemies but let’s prepare for this already.

If there still are enemies, we try to attach another bullet. Remember that the attachBullets method returns YES if there are more bullets to attach and NO otherwise. So, if there are more bullets I run a cocos2d action that resets the position of the view to the left half of the scene so I can see my catapult again.

If there are no more bullets we’ll have to reset the whole scene, but this will come later on. Let’s have some fun first.

We now have to call this method at an appropriate time. But what is this appropriate time. Maybe when the bullet finally stops moving after we released it? Maybe a few seconds after we hit the first target? Well, that’s all open for discussion. To keep things simple for now, let’s call this method a few seconds after we release the bullet.

As you remember we do this on the tick method when we destroy the weld joint. So go to that method and find the DestroyJoint call we added and add this line right after:

This will wait 5 seconds and then call resetBullet. Now run the project and watch the mayhem!

One last thing for this section. The mayhem is not very natural in my opinion because of one little detail: the objects that collide with the right border of the scene all stay there as if leaning against a wall but there’s no wall there in our world. The objects should fall to the right of the scene but they don’t.

This happens because when we build our world (well, actually this came with the initial cocos2d project) we added fixtures to the 4 corners of the scene. We now can see that the right corner probably should not exist.

It’s Raining Cats and Dogs

We’re almost there! All we need now is a way to detect that the enemies should be destroyed.

We can do this using collision detection but there’s a little problem with a simple collision detection. Our enemies are already colliding with the blocks so simply detecting if the enemies are colliding with something is not enough because the enemies would be destroyed right away.

We could say that for the enemies to be destroyed they have to collide with a bullet. This would be very easy to do but then some enemies would be very hard to destroy. Take the dogs between the two blocks on our scene. It’s very hard to hit it with a bullet but it’s not hard if we throw one of the blocks at it. But we already established that a simple collision with the blocks is not going to work.

What we can do is try to determine the strength of the collision and then determine that we have to destroy an enemy based on a minimum strength.

To do this using Box2d we have to create a contact listener. Ray already explained how to create one during the second part of the breakout game tutorial. So if you haven’t read the tutorial or don’t remember it go ahead and read at least the beginning of this second part. I’ll wait….

There will be some differences though. First we will use a std::set instead of a std::vector. The difference is that the set does not allow duplicate entries so if we have multiple impacts on a target we don’t have to worry about adding them twice to our list.

Another difference is that we’ll have to use the postSolve method as this is where we’ll be able to retrieve the impulse of a contact and thus determine if we have to destroy an enemy.

Control-click on your main classes folder and choose New File. Click iOS\C and C++ on the left, choose “C++ file”, and click Next. Name your file MyContactListener.cpp, and click Save. If it created a .h for you too you’re set, otherwise repeat the above but select “Header File” to create a header file called MyContactLister.h as well.

First we determine if the contact we’re processing involves at least one enemy. Remember on the createTarget method that we “tagged” the enemies using the fixture’s userData? That’s why we did it. See, I told you you’d understand soon.

Every contact can have one or more contact points and every contact point has a normal impulse. This impulse is basically the force of the contact. We then determine the maximum impact force and determine if this should destroy the enemy.

If we determine we should destroy the enemy we add the body object to our set so we can destroy it later. Remember that, as Ray said on his tutorial, we can’t destroy the enemy’s body during the contact processing. So we hold this on our set and will process it later.

The value I used as the impulse that should destroy the enemy is something you’ll have to test for yourself. This will vary depending on the masses of the objects, the speed the bullet is impacting and some other factors. My suggestion is to start small and increase the value to determine what’s an acceptable value for your gameplay.

Now that we have our listener code let’s instantiate and use it. Go back to HelloWorldLayer.h and add the include of our new C++ class to the imports:

#import "MyContactListener.h"

And add a variable to hold our listener:

MyContactListener *contactListener;

No go to the implementation file and add this o the end of the init method:

We simply iterate though the set of our contact listener and destroy all the bodies and their associated sprites. We also remove them from the enemies and targets NSSet so we can determine if we have eliminated all the enemies.

Finally we clear the contact listener’s set to make it ready for the next time tick gets called and so that we don’t try to destroy those bodies again.

Go ahead and run the game. I promise you it’s even cooler now!

But you can say there’s something missing here. Something that really tell us we destroyed those freaking enemies. So let’s add some polish to our game and make these little squirrel haters explode.

Cocos2d will make it very easy to do this using particles. I won’t go into a lot of details here since this topic can even have a tutorial of it’s own. If you want to dig deeper on this topic you can have a look at Chapter 14 of Rod and Ray’s Cocos2d book. In the meantime I’ll show you how to do this and how to try out other cocos2d built-in particles.

We first store the position of the enemy’s sprite so we know where to add the particle. Then we add an instance of CCParticleSun in this position. Pretty easy right? Go ahead and run the game!

Pretty cool, right?

CCParticleSun is one of many pre-configured CCParticleSystem sub-classes that comes with cocos2d. Command-click on CCParticleSun in Xcode and you’ll be taken to the CCParticlesExamples.m file. This file has a lot of sub-classes of CCParticleSystem that you can experiment with. And you may think that CCParticleExplosion would look better for us but you’d be wrong, at least in my opinion. But go ahead and try it out with a bunch of particle systems and see what happens.

One thing that I sneaked up on you is the texture file used on this particle. If you look inside the code for CCParticleSun you’ll notice it uses a file called fire.png. This file was already added to the project some time ago when we added all the image files.

Finishing Touches

Before we wrap this up let’s add a way to reset everything in case we run out of bullets or enemies. This is gonna be pretty easy as we have most of our scene creation in separate methods anyway.

The best way to reset our game would be to call resetGame. But if you simply do this you’ll end up with a bunch of old targets and enemies on your scene. So we’ll have to add some cleanup to our resetGame method to take care of this. Fortunately we have kept references of everything so it’s gonna be pretty easy.

This is pretty simple. We just go through the sets we have and remove the bodies and the associated sprites from the scene. The conditional is because we will not have the sets defined the first time we call this method because we didn’t create anything yet.

Now let’s call resetGame at the appropriate times. If you remember we left some conditions blank on our resetBullet method. Well, this is the appropriate place. So go there and replace the two comments we left about doing something later for this:

Run the game and you’ll see that when the enemies or the bullets run out the game will reset and you’ll be able to play it again without having to re-run the project.

Let’s add just one more nice little detail to our game. When the game starts you can’t see the targets so you don’t know what you have to destroy. Let’s fix this, again, changing something on resetGame.

Now we’ll create the bullets and targets and then start a sequence of actions. These actions will run one after the other.

The first will move our scene to the right so we can see our targets. When this movement finishes we’ll call the method that attaches the bullet. This will make the bullet get attached when we’re not seeing it so we’ll avoid the very crude attachment we have now. Then we’ll wait a second so you can get your strategy straight.

And finally… we’ll move back to the left so you can start the destruction!

Want More?

I had a blast working on this tutorial, and everyone I showed it to really liked it (or are all really nice to me!)

If you guys are interested, I’d love to keep working on this some more and make a full “Catapult Game Starter Kit” for sale on this site, kind of like the Space Game Starter Kit.

The full Catapult Game Starter Kit would take the above tutorial and game and expand it to include the following features:

Adding finger scrolling to review the scene

New artwork and enemies!

Sound effects, music, and animation!

Tons polish to make the game feel better

Using LevelHelper to easily create multiple levels

Adding a neat level selection scene

Adding a title scene and main menu

Creating power ups

Scores and Game Center support!

Anything else you guys want (post if you have an idea!)

Before I put the time and energy into creating this though, I’d like to check if this is something you’re interested in.

Could you please answer the following poll to let me know if this is something you’d like?

Yes - would purchase for $77

No - would not purchase for $77

Undecided

Loading ...

It’s OK if you’re not interested, so please answer honestly! I enjoy working on this but have plenty of other stuff to keep me busy :]

Where To Go From Here?

The repository tag for this point in the tutorial is FinalTouches. You can download the whole project here or get it at any point here.

What a trip right? From a few block to some destruction and flying acorns in no time.

If you feel adventurous and want to work on this code some more there are some known issues that are somewhat easy to solve and that can be a good exercise. Check out the issues page of the repository.

If you have any questions or comments or want to join in on improving this game, please join the forum discussion below!

This is a blog post by iOS Tutorial Team member Gustavo Ambrozio, a software engineer with over 20 years experience, including over three years of iOS experience. He is the founder of CodeCrop Software. You can also find him on Google+.

Ray is part of a great team - the raywenderlich.com team, a group of over 100 developers and editors from across the world. He and the rest of the team are passionate both about making apps and teaching others the techniques to make them.

When Ray’s not programming, he’s probably playing video games, role playing games, or board games.

i tried changing a little bit of code so the blocks can be destroyed, however i still cannot figure how to change the "resistance" of certain blocks, also i would like to change the angle of the shoot, instead of just shooting straight, and i don't know if it could be possible to "trace" the trajectory of the acorn before the shoot, kinda like peggle.

thanks for the tutorial and i'm looking forward for this game starter kit

Some serious conversations here about money. Jesus! I am from Bangladesh where $50 is the rent for a decent two bed-room unit. If the price was even $1, it would buy two good meals. It doesn't matter what the price is, some people will never able to afford it. That doesn't mean people have to work hard and give you something for free. It doesn't make sense. I love the tutorial as it is and there's always a way to add/modify as long as you understand the root concept. Thanks for the tutorials. Don't decrease the price. You already wrote a friggin cool tutorial for free. That's enough courtesy.

Saj wrote:Some serious conversations here about money. Jesus! I am from Bangladesh where $50 is the rent for a decent two bed-room unit. If the price was even $1, it would buy two good meals. It doesn't matter what the price is, some people will never able to afford it. That doesn't mean people have to work hard and give you something for free. It doesn't make sense. I love the tutorial as it is and there's always a way to add/modify as long as you understand the root concept. Thanks for the tutorials. Don't decrease the price. You already wrote a friggin cool tutorial for free. That's enough courtesy.

Thank you.

Saj is right! $50 is a bargain. You get so much for free here, one should pay a deceint amount for some extra matterial. If you are one who can not afford it than look around the site and learn everything, it's a gold mine! Also, it might be a good investment. Ex. Purchasing Level Helper saved me ages of coding. I would have never heard of it if not for this site. One should be wise when spendig but should pay for the shortcuts that others had worked on. I say this when in my country $50 is a quater of the average monthly salary.

rwenderlich wrote:The arc is all about the direction/length of the impulse on the acorn when you shoot it out, and the density of the acorn and the gravity. Try tweaking these a bit to get the behavior you want.

hmmm. I don't see where you do this. Can you provide some code?
Thanks.