-
5/27/2018 How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich.pdf
1/18
4/7/14How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich
Pahttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial
Pew pew ninja strike!
How To Make A Simple iPhone Game
with Cocos2D 3.0 Tutorial
Note from Ray: This tutorial is a 2014 reboot of the classic How To
Make A Simple iPhone Game Cocos2D 2.0 Tutorial.
What better way to celebrate the brand new 3.0 release of Cocos2D
than with a fresh update to a classic tutorial!
Cocos2D 3.0 is the latest version of the hugely popular open source
iOS framework for developing 2D games, including thousands of App
Store games and many top 10 hits.
It has great sprite support, a deeply integrated version of the excel-
lent Chipmunk2D physicslibrary, OpenAL sound library, fun effects,
and loads more.
In this Cocos2D 3.0 tutorial for beginners, you will learn how to cre-
ate a simple and fun 2D game for your iPhone from start to finish. If
youve previously followed the Cocos2D 2.0 Tutorial, then this may
feel familiar however you will be utilizing the integrated physics en-
gine to take it to the next level.
You can either follow along with this tutorial or just jump straight to
the sample project source at the end. And yes, there will be blood, I
mean ninjas!
Cocos2D vs Sprite Kit
Before you get started, you may be thinking, Hey, why bother with Cocos2D now that I have Apples Sprite Kit? Do I re
want to try anything else?
Well, as with any game framework, there are a few pros and cons of Cocos2D.
Cocos2D Pros
Pro:You are not locked into the iOS ecosystem, want to port your game to Android? Its your choice and you can
now typically do it with Cocos2D in one line!
Pro:You can write your custom OpenGL effects code.
Pro:Its Open Source, so if you want to change something or find out how it works, you can dig right into the sou
code.
Martin Walsh on January 21, 2014
http://cdn4.raywenderlich.com/wp-content/uploads/2014/01/Cocos2D3.pnghttp://cdn4.raywenderlich.com/wp-content/uploads/2014/01/Cocos2D3.pnghttp://chipmunk-physics.net/http://cdn4.raywenderlich.com/wp-content/uploads/2014/01/Cocos2D3.pnghttp://cdn4.raywenderlich.com/wp-content/uploads/2014/01/Cocos2D3.pnghttp://cdn4.raywenderlich.com/wp-content/uploads/2014/01/Cocos2D3.pnghttp://cdn4.raywenderlich.com/wp-content/uploads/2014/01/Cocos2D3.pnghttp://cdn4.raywenderlich.com/wp-content/uploads/2014/01/Cocos2D3.pnghttp://cdn4.raywenderlich.com/wp-content/uploads/2014/01/Cocos2D3.pnghttp://www.raywenderlich.com/u/cocojoehttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorialhttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorialhttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorialhttp://www.raywenderlich.com/u/cocojoehttp://www.raywenderlich.com/42699/spritekit-tutorial-for-beginnershttp://chipmunk-physics.net/http://www.raywenderlich.com/25736/how-to-make-a-simple-iphone-game-with-cocos2d-2-x-tutorialhttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorialhttp://cdn4.raywenderlich.com/wp-content/uploads/2014/01/Cocos2D3.pnghttp://www.raywenderlich.com/u/cocojoe -
5/27/2018 How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich.pdf
2/18
4/7/14How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich
Pahttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial
Cocos2D Cons
Con:Its not built into Xcode, so you will have to download and run the Cocos2D installer.
Con:It doesnt currently have a built-in texture and particle tool editor (however, it does have great 3rd Party too
support).
Cocos2D has an established community and there are loads of existing tutorials, books and code samples out there. C
cos2D is developed and maintained by game developers who aim to make it easier for you to get on with making grea
games.
Installing Cocos2D
Cocos2D 3.0 comes with a new installer, so getting started has never
been easier!
Just download the latest Cocos2D installer(version 3 or later), open
the DMG and double click the installer. This will automatically install
the Cocos2D templates for Xcode and build the Cocos2D Xcode docu-
mentation.
You will see a bunch of messages as the installer runs, once finished it
will open up the Cocos2D welcome page. Congrats youre now ready
to work with Cocos2D!
Hello World
Lets start by getting a simple Hello WorldHello Worldproject up and running
by using the Cocos2D template that was installed in the previous step.
Open Xcode, select File\New Project, select the iOS\cocos2d v3.x\cocos2d iOStemplate and click Next:
http://www.cocos2d-iphone.org/getting-started/ -
5/27/2018 How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich.pdf
3/18
4/7/14How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich
Pahttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial
Enter Cocos2DSimpleGamefor the Product Name, select iPhonefor Devices and click Next:
-
5/27/2018 How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich.pdf
4/18
4/7/14How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich
Pahttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial
Choose somewhere on your drive to save the project and click Create. Then click the play button to build & run the
project as-is. You should see the following:
-
5/27/2018 How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich.pdf
5/18
4/7/14How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich
Pahttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial
Tap the Simple Spritebutton to reveal another test scene, which you will be working with in this tutorial:
Cocos2D is organized into the concept of sceneswhich you can think about kind of like
-
5/27/2018 How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich.pdf
6/18
4/7/14How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich
Pahttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial
screens for a game. The first screen with the HelloWorld menu is the IntroScene, and the second screen with the sp
ning Cocos2D logo is the HelloWorldScene. Lets take a closer look at this.
Enter the Ninja!
Before the Ninja can make his grand entrance, you will need some artwork to work with
First step, download the resource packfor this project. Unzip the file, and drag the ResourcePackfolder into the Xcod
project. Make sure that the Copy items into destination groups folder (if needed)option is checked and that youCocos2DSimpleGametarget is selected.
Second, open HelloWorldScene.m. Remember, this is the code for the screen with the spinning Cocos2D logo, and th
will be a nice spot to start building the game. Take a look at the template code before you modify it:
@implementationHelloWorldScene { // 1 CCSprite *_sprite;}
-(id)init { // 2
self =[super init]; if(!self)return(nil);
// 3 self.userInteractionEnabled =YES;
// 4 CCNodeColor *background =[CCNodeColor nodeWithColor:[CCColor colorWithRed:0.2fgreen:0.2f blue:0.2f alpha:1.0f]]; [self addChild:background];
// 5 _sprite =[CCSprite spriteWithImageNamed:@"Icon-72.png"]; _sprite.position =ccp(self.contentSize.width/2,self.contentSize.height/2); [self addChild:_sprite];
// 6 CCActionRotateBy*actionSpin =[CCActionRotateBy actionWithDuration:1.5f angle:360]; [_sprite runAction:[CCActionRepeatForever actionWithAction:actionSpin]];
// 7 CCButton *backButton =[CCButton buttonWithTitle:@"[ Menu ]"fontName:@"Verdana-Bold"fontSize:18.0f]; backButton.positionType =CCPositionTypeNormalized; backButton.position =ccp(0.85f, 0.95f); // Top Right of screen
[backButton setTarget:self selector:@selector(onBackClicked:)]; [self addChild:backButton];
returnself;}
Lets go over this step-by-step:
1. Declare a private instance variable for the sprite for the Cocos2D logo, makes it easy to access the sprite later on
2. Initialization of the HelloWorldHelloWorldscene.
http://cdn3.raywenderlich.com/downloads/Cocos2DSimpleGameResourcePack.zip -
5/27/2018 How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich.pdf
7/18
4/7/14How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich
Pahttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial
3. This is how you configure a scene to receive touch events in Cocos2D. This means that the touchBegan:withtouchBegan:with
Event:Event:method will be called, which youll see later on in this file.
4. Creates a CCNodeColorCCNodeColor, which is simply a node that displays a single color (dark gray in this case). Once this n
is created, it needs to be added to the scene with the addChild:addChild:method so you can see it. Now your scene ha
background color!
5. Create a CCSpriteCCSpritewith the spriteWithImageNamed:spriteWithImageNamed: method to load the image resource. The position o
the sprite is set to the center of the screen by using the dimensions of the screen. Again this needs added to thescene using the addChild:addChild:method.
6. Create a CCActionRotateByCCActionRotateByaction that will be used to spin the sprite 360 degrees and using the CCActionCCAction
RepeatForeverRepeatForeverto repeat the rotation action. This action is then applied to the sprite using the runActionrunAction
method. Actions are a very powerful feature of Cocos2D that will be discussed later.
7. Create a CCButtonCCButtonthat will navigate back to the IntroScenewhen clicked, you can be use this as a simple way
restart the scene.
OK, great! As a first step, lets replace the spinning Cocos2D logo with a spinning ninja instead.
How do you think youd do that? Here are some hints:
Have a look in the ResourcePackthat you recently added to the project to find the ninja image.
You only have to modify one line of code!
Try and do it yourself if you can, but if you get stuck heres the solution:
Solution Inside Show
That was easy,_sprite_spriteis a pretty obvious name however it may get a little confusing if you start using_sprite1_sprite1,
_sprite2_sprite2so change the name_sprite_spriteto_player_player. Find the first entry in @implementation@implementation:
@implementationHelloWorldScene { // 1 CCSprite *_sprite;}
And change this to:
@implementationHelloWorldScene { // 1 CCSprite *_player;}
Shortly after you do this, Xcode will flag the code as having 5 errors and highlight these lines in red. No need to worry,
just informing you that _sprite is not longer valid as you renamed the object to _player. So go ahead and change all thother_sprite_spritereferences to_player_player.
Lets see what ninjas do when they are not fighting monsters, build and run the project.
http://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial -
5/27/2018 How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich.pdf
8/18
4/7/14How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich
Pahttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial
The spinning Cocos2D logo is now replaced with a spinning ninja. Thankfully ninjas can not get dizzy.
However, a ninja does train their entire life for combat, so next you will want to add some monsters to challenge your
ninja!
A Wild Monster Appears
Next you want to add some monsters into your scene. A static monster is of course no challenge to an experienced ni
so to make things a bit more interesting you will add some movement to the monsters. You will create the monsters
slightly off screen to the right and set up a CCActionfor them, telling them to move from right to left.
Add the following code to HelloWorldScene.m:
-(void)addMonster:(CCTime)dt {
CCSprite *monster =[CCSprite spriteWithImageNamed:@"monster.png"];
// 1 intminY =monster.contentSize.height /2; intmaxY =self.contentSize.height -monster.contentSize.height /2; intrangeY =maxY -minY; intrandomY =(arc4random()%rangeY)+minY;
// 2 monster.position =CGPointMake(self.contentSize.width +monster.contentSize.width/2,randomY); [self addChild:monster];
-
5/27/2018 How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich.pdf
9/18
4/7/14How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich
Pahttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial
// 3
intminDuration =2.0; intmaxDuration =4.0; intrangeDuration =maxDuration -minDuration; intrandomDuration =(arc4random()%rangeDuration)+minDuration;
// 4 CCAction *actionMove =[CCActionMoveTo actionWithDuration:randomDuration position:CG-PointMake(-monster.contentSize.width/2, randomY)]; CCAction *actionRemove =[CCActionRemove action]; [monster runAction:[CCActionSequence actionWithArray:@[actionMove,actionRemove]]];}
Lets go over this step-by-step:
1. Define a vertical range for the monster to spawn. When you place a sprite, by default you are placing the center
the sprite. So here you take the screen height and reduce it by the monsters height, so the monster doesnt end
being cut off.
2. Position the monster slightly off screen to the right, take the screen width and add the monsters width to ensure
its just hidden off screen.
3. Now you want to decide how long it takes (in seconds) for the monster to move across the screen, lets randomis
to make the monsters less predictable.
4. You will use the Cocos2D action CCActionMoveTo:CCActionMoveTo:to animate moving the monster from the starting point
(slightly off screen right) to the target destination point (slightly off screen left) causing it to move quickly across t
screen from right to left.
You have already seen actions in action with the spinning however Cocos2D provides a lot of extremely handy built-in
tions, such as move actions, rotate actions, fade actions, animation actions and many more. Here you use three action
on the monster:
CCActionMoveTo: This action is used to control the movement of the monster, in this case moving across thescreen from right to left. The duration of the action is also specified which controls how long it takes for the mon
ster to move across the screen. The shorter the duration the faster the monster will appear to move. In this case
you randomize the duration between 2 and 4 seconds.
CCActionRemove: Handy action that removes a node from its parent, effectively deleting it from the scene. You
use this action to remove the monster from the scene when it is no longer visible (slightly off screen left). This is
very important because otherwise you would eventually have tens of thousands of monsters trying to take over
your iPhone and consume all device resources.
CCActionSequence : The sequence action allows you to chain together a sequence of actions that are performed
order, one at a time. This way you can have the CCActionMoveToCCActionMoveToaction perform first and once it is complete
perform the next action CCActionRemove. This is a very powerful action allowing you to create complex animatsequences.
Great, so now you have a method to add a monster to your scene. However one monster is hardly a challenge for an e
perienced ninja, lets create a timed monster spawn method.
Cocos2D features a scheduler that allows you to setup callbacks every X.X seconds, so you can setup a monsters spaw
generator to add new monsters every X seconds.
Open up HelloWorldScene.mand add the following code just after [super onEnter];[super onEnter];in the onEnteronEntermethod
-
5/27/2018 How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich.pdf
10/18
4/7/14How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich
Paghttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial
[self schedule:@selector(addMonster:)interval:1.5];
This will add a Cocos2D scheduler timer to call the previously added addMonster:addMonster:method every 1.5 seconds.
Note that when you created the addMonsteraddMonstermethod, there was an additional dtdtparameter. This stands for delta
time, and represents the time difference between the previous and the current frame. The scheduler requires that eve
method it calls takes this as a parameter, however you will not use it in this tutorial.
Before you see these monsters in action, you will make a couple of changes. Lets bring everyone out of the shadows a
little. Why not change the background color from a dark grey to a lighter grey?
Solution Inside Show
Your ninjas head must be spinning by now, can you stop him spinning and also move him over to the left a bit so he ca
prepare himself for the oncoming frontal assault?
Solution Inside Show
Build and run, and you should now see monsters fly across the screen!
Hadouken
Unfortunately your ninja is still not at a high enough level to cast a fireball, so you will need to rely on your expert thro
ing skills to defeat those evil (or possibly just misunderstood) monsters.
http://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorialhttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial -
5/27/2018 How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich.pdf
11/18
4/7/14How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich
Paghttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial
Grab yourself a shuriken and lets add some projectile action.
You will be using the CCActionMoveTo:CCActionMoveTo:again, its not however quite as simple as moving to the touch point and st
ing from the_player.position_player.position. You want to throw the projectile across the screen in the direction of the touch. S
you have to use a little math.
You have a smaller triangle created by the x and y offset from the origin point to the touch point. You just need to mak
big triangle with the same ratio and you know you want one of the endpoints to be off the screen.
To perform these calculations, it really helps if you have some basic vector math routines available (like methods to ea
add and subtract vectors). Cocos2D includes a handy set of vector manipulation functions such as ccpAddccpAddand ccpSccpS
vectors.
If youre unsure about any of the following calculations, check out this quick vector math explanation. I would persona
recommend the excellent Khan Academyvideo tutorials on the subject.
You got the touch!
The HelloWorldSceneHelloWorldScenetemplates already comes touch enabled as you saw in the initinitmethod.
// 3self.userInteractionEnabled =YES;
To handle these touches you typically need to create a touchBegan:touchBegan:method however the default template kindly
comes with a simple touchBegantouchBeganmethod example.
Open HelloWorldScene.mand replace the current touchBegan:touchBegan:method with the following snippet:
https://www.khanacademy.org/math/linear-algebra/vectors_and_spaces/vectors/v/vector-introduction-linear-algebrahttp://www.mathsisfun.com/algebra/vectors.html -
5/27/2018 How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich.pdf
12/18
4/7/14How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich
Paghttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial
-(void)touchBegan:(UITouch *)touch withEvent:(UIEvent *)event { // 1 CGPoint touchLocation =[touch locationInNode:self];
// 2 CGPoint offset =ccpSub(touchLocation, _player.position); float ratio =offset.y/offset.x; int targetX =_player.contentSize.width/2+self.contentSize.width; int targetY =(targetX*ratio)+_player.position.y; CGPoint targetPosition =ccp(targetX,targetY);
// 3 CCSprite *projectile =[CCSprite spriteWithImageNamed:@"projectile.png"]; projectile.position =_player.position; [self addChild:projectile ];
// 4 CCActionMoveTo *actionMove =[CCActionMoveTo actionWithDuration:1.5f position:tar-getPosition]; CCActionRemove *actionRemove =[CCActionRemove action]; [projectile runAction:[CCActionSequence actionWithArray:@[actionMove,actionRemove]]];
}
Lets go over this step-by-step:
1. You need to translate the screen touch into the scenes coordinate system. There is a handy Cocos2D category on
UITouch with locationInNode:locationInNode:that will do this.
2. So as you can see, you have a small triangle created by the x and y offset from the origin point to the touch point
You just need to make a big triangle with the same ratio and you know you want one of the endpoints to be off
the screen.
3. Create the projectile sprite and set it to start at the same position as the player. This is why you made_player_player
private instance variable so you could access it easily later.
4. You should now be more familiar with the CCActionMoveToCCActionMoveTonow. You have the previously calculated target po
and the duration is the time taken for the projectile to reach this point, so the lower it is, the faster your projectil
will travel.
Build and run, and fire at will!
-
5/27/2018 How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich.pdf
13/18
4/7/14How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich
Paghttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial
Arggghhh these monsters are too strong, why wont they just die already!
Collision Detection and Physics
So you have a ninja, monsters and projectiles flying all over the screen. It looks good but it would be a lot more fun wit
bit of impact, for that you need collision detection between your projectiles and your monsters.
One of the great new features of Cocos2D 3.0 is the deeply integrated physics engine, making this task a breeze. Phys
engines are great for simulating realistic movement, however they are also very useful for handling collision detection
You are now going to use the Cocos2D physics engine to determine when monsters and projectiles collide. There are f
steps to do this:
Set up the physics world. A physics world is the simulation space for running physics calculations. You will set o
up for the scene and modify a few properties like gravity. The physics world is then added to your scene. You wil
modify the existing game objects so they are added to the physics world so they will be part of the physics simul
tion.
Create physics bodies for each sprite. In Cocos2D you can associate a physics body to each sprite for collision
tection purposes and set certain properties on it. Note that the physics body does not have to be the exact same
shape as the sprite. Usually its a simpler shape such as a box or circle, rather than a pixel-perfect outline. Since t
is generally good enough for most games and offers better physics performance.
Set CollisionType for each type of sprite.One of the handy features of Cocos2D physics is you dont have to pl
around with integer bitmasks to define your collision types. You can set an easily readable string to define your c
sion types.
-
5/27/2018 How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich.pdf
14/18
4/7/14How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich
Paghttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial
Set a collision handler delegate.By default when two physics bodies collide they will be handled by the physics
simulation however you will want to do something when a projectile collides with a monster such as kill the mon
ster. So you will be adding a collision handler delegate to handle the collision between your monster and project
collision types.
Lets get started. First, you will now need to add another private instance variable for you physics world.
Ensure you have HelloWorldScene.mopen and add the following to the @implementation HelloWorldScen@implementation HelloWorldScen
declaration after your CCSpriteCCSprite.
CCPhysicsNode *_physicsWorld;
Now you need to setup the physics simulation and add it to your scene, add the following code after the CCNodeColCCNodeCol
in the initinitmethod.
_physicsWorld =[CCPhysicsNode node];_physicsWorld.gravity =ccp(0,0);_physicsWorld.debugDraw =YES;_physicsWorld.collisionDelegate =self;[self addChild:_physicsWorld];
Gravity is set to (0,0) as you are using the physics simulation primarily for collision detection. Cocos2D has some hand
debug functionality, the debugDrawdebugDrawflag is really useful to help visualise your physics world. You will be able to see a
physics bodies added to the simulation. You are also setting the collisionDelegatecollisionDelegateto selfself, this allows you to a
collision Handlers to the scene and the physics simulation knows to look in HelloWorldSceneHelloWorldScenefor these handlers.
You will notice that Xcode will throw up a warning around the collisionDelegatecollisionDelegateline; this is easily resolved. Op
HelloWorldScene.hand mark the interface as implenting the CCPhysicsCollisionDelegateCCPhysicsCollisionDelegate .
@interfaceHelloWorldScene :CCScene
Now you need to set up the player with a physics body and add the player to the_physicsWorld_physicsWorldinstead of directl
the scene.
Back in HelloWorldScene.m, find the following code in the initinitmethod:
[self addChild:_player];
Replace that code with the following:
_player.physicsBody =[CCPhysicsBody bodyWithRect:(CGRect){CGPointZero, _player.content-Size}cornerRadius:0]; // 1
_player.physicsBody.collisionGroup =@"playerGroup"; // 2[_physicsWorld addChild:_player];
Quick review of this code snippet:
1. Creates a physics body, in this case a box using the players contentSizecontentSizeto create an bounding box rectangle
around the player.
2. Set physics body collisionGroupcollisionGroup, by default everything will collide. If you set physics bodies to the same coco
lisionGrouplisionGroupthey will no longer collide with each other, this is handy when you have a player that is made up
multiple bodies but you dont want these bodies to collide with each other, for example a player holding a weapo
You will use this to ensure the projectile does not collide with the player.
You have setup physics simulation and created a player physics body and added it to the simulation. Now see if you ca
do this yourself, by adding the monster to the physics simulation.
-
5/27/2018 How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich.pdf
15/18
4/7/14How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich
Paghttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial
Solution Inside Show
This is nearly identical to creating the_player_playerphysics body, but I was being a little tricky as I introduced a new prop
ty. This time you are setting the collisionTypecollisionTypeproperty, this will be used in setting up a physics simulation collisi
delegate between the monsterCollision and the projectileCollsion collisionTypecollisionType.
You are nearly there now! This time, see if you can add the projectile to the simulation. Ill give you a clue: it will use bo
the collisionTypecollisionTypeand the collisionGroupcollisionGroupproperties.
Solution Inside Show
Build and run, and you should see a lot of pretty pink boxes:
The pink boxes around the sprites are created by the_physics_physicsproperty debugDrawdebugDraw. They are handy when you ar
first setting up your physics, so you can make sure that its all working as you expect. Notice that the box around the
shuriken doesnt look so great; it would much better if it used a circle.
There is of course a method you can use to create a circular body shape bodyWithCircleOfRadius:bodyWithCircleOfRadius: which is a
much better fit for your projectile. Replace the projectile body code with the following:
projectile.physicsBody =[CCPhysicsBody bodyWithCircleOfRadius:projectile.content-Size.width/2.0f andCenter:projectile.anchorPointInPoints ];
By default the center point will be at the bottom left of the sprite however you want the circle to be placed in the midd
of your sprite.
http://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorialhttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial -
5/27/2018 How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich.pdf
16/18
4/7/14How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich
Paghttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial
Great, you have now modified your game objects to be part of the physics simulation. Now you really want to be able
execute some of your own code when the projectileCollisionprojectileCollision and monsterCollisonmonsterCollisoncollisionTypecollisionType
make contact.
The Cocos2D physics engine has some really nice functionality to do this. Just add the following method into HelloWo
Scene.m:
-(BOOL)ccPhysicsCollisionBegin:(CCPhysicsCollisionPair *)pair monsterCollision:(CCNode
*)monster projectileCollision:(CCNode *)projectile { [monster removeFromParent]; [projectile removeFromParent]; returnYES;}
That snippet of code is pretty powerful. When the physics simulation is set up, the physics engine will check for CC-CC-
PhysicsCollisionDelegatePhysicsCollisionDelegate methods and call them if they exist. The parameter names will be taken to be the
lisionTypes you want to deal with yourself.
In this method you are completely removing both the projectile and monster nodes from the simulation and scene. Y
could of course add a score counter, apply a special effect or anything else you would like to do each time a projectile
lides with monster.
Build and run and you finally should be able to destroy those monsters. Go go power ninja!
Finishing Touches
Youre pretty close now to having an extremely simple game now. But (Pew-Pew!), a bit of sound would be nice right
about now.
Cocos2D uses the OpenAL sound library for sound support. No need to include any headers manually, its all good to g
History Lesson:For the Cocos2D historians out there wondering what happened to SimpleAudioEngine, that soun
library has now been superseded by Open AL.
Playing a SFX is really easy, time to add a SFX every time the ninja throws his shuriken. The sound may not be a 100% a
curate representation of a ninja throwing a shuriken :-)
Add the following to the end of your projectile creating touchBegan:touchBegan:method.
[[OALSimpleAudio sharedInstance]playEffect:@"pew-pew-lei.caf"];
Time to add a little mood music, add this line to initinit, right after setting userInteractionEnableduserInteractionEnabled to YESYES:
[[OALSimpleAudio sharedInstance]playBg:@"background-music-aac.caf"loop:YES];
As a final step, comment out this line in initinitto turn off debug drawing:
_physicsWorld.debugDraw =YES;
Build and run, pew-pew. You now have sound, how easy was that?
-
5/27/2018 How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich.pdf
17/18
4/7/14How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich
Paghttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial
Where To Go From Here?
And thats a wrap! Heres the full code for the Cocos2D 3.0 gamethat you have developed thus far.
You have covered a lot of ground in this Cocos2D 3.0 tutorial, introducing you to the key areas of Cocos2D. From small
beginnings come great things, so why not take things a bit further and improve upon the project?
Have a look at the code in the IntroSceneyou will see how to create a label. Why not try adding a counter to you
game every time you destroy a monster?
What should happen when a monster collides with the ninja?
Want to try some more advanced animation, In Xcode Open Help\Documentation and API Referencesand
search for CCActionyou will get a list of all the actions available that you can apply to any of your game characte
objects.
Ive never seen a shuriken that didnt spin, how about a little rotation (Im sure weve seen an example of that ear
in this tutorial). Hint: You can use runActionrunActionmore than once on a node. It doesnt have to be in a sequence.
If you want to learn more about Cocos2D, the official Cocos2D forumis a friendly place to ask questions and learn froyears of experience. My username is @cocojoe feel free to come in and say hi.
If you have any questions or comments about this tutorial, please join the discussion below!
http://www.cocos2d-iphone.org/forums/http://cdn1.raywenderlich.com/wp-content/uploads/2014/01/Cocos2DSimpleGame2.zip -
5/27/2018 How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich.pdf
18/18
4/7/14How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial | Ray Wenderlich
Paghttp://www.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial
Martin Walsh
Martin is a software engineer and maker, currently focusing on iOS development. He's the co-
founder of independent games studio Pedroand is passionate both about making cool stuff
and helping others to learn in the process.
Martin is a contributor to the Cocos2D iOS gaming development library and mentor on the
Cocos2D Forum.
http://www.cocos2d-iphone.org/forums/http://visitpedro.com/http://www.raywenderlich.com/u/cocojoe