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 excellent Chipmunk2D physics library, OpenAL sound library, fun effects, and loads more.
In this Cocos2D 3.0 tutorial for beginners, you will learn how to create a simple and fun 2D game for your iPhone from start to finish. If you’ve previously followed the Cocos2D 2.0 Tutorial, then this may feel familiar however you will be utilizing the integrated physics engine 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!
Before you get started, you may be thinking, “Hey, why bother with Cocos2D now that I have Apple’sSprite Kit? Do I really want to try anything else?”
Well, as with any game framework, there are a few pros and cons of Cocos2D.
Cocos2D Pros
Cocos2D Cons
Cocos2D has an established community and there are loads of existing tutorials, books and code samples out there. Cocos2D is developed and maintained by game developers who aim to make it easier for you to get on with making great games.
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 documentation.
You will see a bunch of messages as the installer runs, once finished it will open up the Cocos2D welcome page. Congrats – you’re now ready to work with Cocos2D!
Let’s start by getting a simple Hello World
project 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 iOS template and click Next:
Enter Cocos2DSimpleGame for the Product Name, select iPhone for Devices and click Next:
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:
Tap the Simple Sprite button to reveal another test scene, which you will be working with in this tutorial:
Cocos2D is organized into the concept of scenes which you can think about kind of like
“screens” for a game. The first screen with the HelloWorld menu is the IntroScene, and the second screen with the spinning Cocos2D logo is the HelloWorldScene. Let’s take a closer look at this.
Before the Ninja can make his grand entrance, you will need some artwork to work with…
First step, download the resource pack for this project. Unzip the file, and drag the ResourcePack folder into the Xcode project. Make sure that the “Copy items into destination group’s folder (if needed)”option is checked and that your Cocos2DSimpleGame target is selected.
Second, open HelloWorldScene.m. Remember, this is the code for the screen with the spinning Cocos2D logo, and this will be a nice spot to start building the game. Take a look at the template code before you modify it:
@implementation HelloWorldScene { // 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.2f green: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]; return self; }
Let’s go over this step-by-step:
HelloWorld
scene.touchBegan:withEvent:
method will be called, which you’ll see later on in this file.CCNodeColor
, which is simply a node that displays a single color (dark gray in this case). Once this node is created, it needs to be added to the scene with the addChild:
method so you can see it. Now your scene has a background color!CCSprite
with the spriteWithImageNamed:
method to load the image resource. The position of the sprite is set to the center of the screen by using the dimensions of the screen. Again this needs added to the scene using the addChild:
method.CCActionRotateBy
action that will be used to spin the sprite 360 degrees and using theCCActionRepeatForever
to repeat the rotation action. This action is then applied to the sprite using the runAction
method. Actions are a very powerful feature of Cocos2D that will be discussed later.CCButton
that will navigate back to the IntroScene when clicked, you can be use this as a simple way to restart the scene.OK, great! As a first step, let’s replace the spinning Cocos2D logo with a spinning ninja instead.
How do you think you’d do that? Here are some hints:
Try and do it yourself if you can, but if you get stuck here’s the solution:
// 5 _sprite = [CCSprite spriteWithImageNamed:@"player.png"];
That was easy, _sprite
is a pretty obvious name however it may get a little confusing if you start using_sprite1
, _sprite2
so change the name _sprite
to _player
. Find the first entry in @implementation
:
@implementation HelloWorldScene { // 1 CCSprite *_sprite; }
And change this to:
@implementation HelloWorldScene { // 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, it’s just informing you that _sprite is not longer valid as you renamed the object to _player. So go ahead and change all the other _sprite
references to _player
.
Let’s see what ninjas do when they are not fighting monsters, build and run the project.
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!
Next you want to add some monsters into your scene. A static monster is of course no challenge to an experienced ninja, 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 CCAction for 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 int minY = monster.contentSize.height / 2; int maxY = self.contentSize.height - monster.contentSize.height / 2; int rangeY = maxY - minY; int randomY = (arc4random() % rangeY) + minY; // 2 monster.position = CGPointMake(self.contentSize.width + monster.contentSize.width/2, randomY); [self addChild:monster]; // 3 int minDuration = 2.0; int maxDuration = 4.0; int rangeDuration = maxDuration - minDuration; int randomDuration = (arc4random() % rangeDuration) + minDuration; // 4 CCAction *actionMove = [CCActionMoveTo actionWithDuration:randomDuration position:CGPointMake(-monster.contentSize.width/2, randomY)]; CCAction *actionRemove = [CCActionRemove action]; [monster runAction:[CCActionSequence actionWithArray:@[actionMove,actionRemove]]]; }
Let’s go over this step-by-step:
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 the 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 actions, such as move actions, rotate actions, fade actions, animation actions and many more. Here you use three actions on the monster:
CCActionMoveTo
action perform first and once it is complete perform the next action CCActionRemove. This is a very powerful action allowing you to create complex animation sequences.Great, so now you have a method to add a monster to your scene. However one monster is hardly a challenge for an experienced ninja, let’s 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 spawn generator to add new monsters every X seconds.
Open up HelloWorldScene.m and add the following code just after [super onEnter];
in the onEnter
method.
[self schedule:@selector(addMonster:) interval:1.5];
This will add a Cocos2D scheduler timer to call the previously added addMonster:
method every 1.5 seconds.
Note that when you created the addMonster
method, there was an additional dt
parameter. This stands for delta time, and represents the time difference between the previous and the current frame. The scheduler requires that every 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. Let’s bring everyone out of the shadows a little. Why not change the background color from a dark grey to a lighter grey?
// 2 CCNodeColor *background = [CCNodeColor nodeWithColor:[CCColor colorWithRed:0.6f green:0.6f blue:0.6f alpha:1.0f]];
Your ninja’s head must be spinning by now, can you stop him spinning and also move him over to the left a bit so he can prepare himself for the oncoming frontal assault?
Disable the head spinning CCActionRotateBy
action.
// 6 //CCActionRotateBy* actionSpin = [CCActionRotateBy actionWithDuration:1.5f angle:360]; //[_player runAction:[CCActionRepeatForever actionWithAction:actionSpin]];Change the position of the Ninja.
_player.position = ccp(self.contentSize.width/8,self.contentSize.height/2);
You may wonder why you are dividing the width by 8 (1/8th of the screen). This is because it’s often handy to avoid hardcoding absolute positions, since different devices have different screen sizes and would require you to have different absolute positions per device.
If you are interested to learn more, have a look at the CCButton
position, notice that it uses a differentpositionType
that uses a normalized resolution of 0..1, 0..1 across all devices.
Build and run, and you should now see monsters fly across the screen!
Unfortunately your ninja is still not at a high enough level to cast a fireball, so you will need to rely on your expert throwing skills to defeat those evil (or possibly just misunderstood) monsters.
Grab yourself a shuriken and let’s add some projectile action.
You will be using the CCActionMoveTo:
again, it’s not however quite as simple as moving to the touch point and starting from the _player.position
. You want to throw the projectile across the screen in the direction of the touch. So 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 make a 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 easily add and subtract vectors). Cocos2D includes a handy set of vector manipulation functions such as ccpAdd
and ccpSub
vectors.
If you’re unsure about any of the following calculations, check out this quick vector math explanation. I would personally recommend the excellent Khan Academy video tutorials on the subject.
You got the touch!
The HelloWorldScene
templates already comes touch enabled as you saw in the init
method.
// 3 self.userInteractionEnabled = YES;
To handle these touches you typically need to create a touchBegan:
method however the default template kindly comes with a simple touchBegan
method example.
Open HelloWorldScene.m and replace the current touchBegan:
method with the following snippet:
- (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:targetPosition]; CCActionRemove *actionRemove = [CCActionRemove action]; [projectile runAction:[CCActionSequence actionWithArray:@[actionMove,actionRemove]]]; }
Let’s go over this step-by-step:
locationInNode:
that will do this._player
a private instance variable so you could access it easily later.CCActionMoveTo
now. You have the previously calculated target point and the duration is the time taken for the projectile to reach this point, so the lower it is, the faster your projectile will travel.Build and run, and fire at will!
Arggghhh these monsters are too strong, why wont they just die already!
So you have a ninja, monsters and projectiles flying all over the screen. It looks good but it would be a lot more fun with a 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. Physics 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 four steps to do this:
Let’s get started. First, you will now need to add another private instance variable for you physics world.
Ensure you have HelloWorldScene.m open and add the following to the @implementation HelloWorldScene
declaration after your CCSprite
.
CCPhysicsNode *_physicsWorld;
Now you need to setup the physics simulation and add it to your scene, add the following code after theCCNodeColor
in the init
method.
_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 handy debug functionality, the debugDraw
flag is really useful to help visualise your physics world. You will be able to see any physics bodies added to the simulation. You are also setting thecollisionDelegate
to self
, this allows you to add collision Handlers to the scene and the physics simulation knows to look in HelloWorldScene
for these handlers.
You will notice that Xcode will throw up a warning around the collisionDelegate
line; this is easily resolved. Open HelloWorldScene.h and mark the interface as implenting theCCPhysicsCollisionDelegate
.
@interface HelloWorldScene : CCScene <CCPhysicsCollisionDelegate>
Now you need to set up the player with a physics body and add the player to the _physicsWorld
instead of directly to the scene.
Back in HelloWorldScene.m, find the following code in the init
method:
[self addChild:_player];
Replace that code with the following:
_player.physicsBody = [CCPhysicsBody bodyWithRect:(CGRect){CGPointZero, _player.contentSize} cornerRadius:0]; // 1 _player.physicsBody.collisionGroup = @"playerGroup"; // 2 [_physicsWorld addChild:_player];
Quick review of this code snippet:
contentSize
to create an bounding box rectangle around the player.collisionGroup
, by default everything will collide. If you set physics bodies to the same collisionGroup
they will no longer collide with each other, this is handy when you have a player that is made up of multiple bodies but you don’t want these bodies to collide with each other, for example a player holding a weapon. 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 can do this yourself, by adding the monster to the physics simulation.
Look inside the addMonster: method and locate the following code:
[self addChild:monster];Replace with:
monster.physicsBody = [CCPhysicsBody bodyWithRect:(CGRect){CGPointZero, monster.contentSize} cornerRadius:0]; monster.physicsBody.collisionGroup = @"monsterGroup"; monster.physicsBody.collisionType = @"monsterCollision"; [_physicsWorld addChild:monster];
This is nearly identical to creating the _player
physics body, but I was being a little tricky as I introduced a new property. This time you are setting the collisionType
property, this will be used in setting up a physics simulation collision delegate between the ‘monsterCollision’ and the ‘projectileCollsion’collisionType
.
You are nearly there now! This time, see if you can add the projectile to the simulation. I’ll give you a clue: it will use both the collisionType
and the collisionGroup
properties.
Look inside the touchBegan:withEvent method and locate find the following code:
[self addChild:projectile];Replace with:
projectile.physicsBody = [CCPhysicsBody bodyWithRect:(CGRect){CGPointZero, projectile.contentSize} cornerRadius:0]; projectile.physicsBody.collisionGroup = @"playerGroup"; projectile.physicsBody.collisionType = @"projectileCollision"; [_physicsWorld addChild:projectile];
Build and run, and you should see a lot of pretty pink boxes:
The pink boxes around the sprites are created by the _physics
property debugDraw
. They are handy when you are first setting up your physics, so you can make sure that it’s all working as you expect. Notice that the box around the shuriken doesn’t 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:
which is a much better fit for your projectile. Replace the projectile body code with the following:
projectile.physicsBody = [CCPhysicsBody bodyWithCircleOfRadius:projectile.contentSize.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 middle of your sprite.
Great, you have now modified your game objects to be part of the physics simulation. Now you really want to be able to execute some of your own code when the projectileCollision
andmonsterCollison
collisionType
make contact.
The Cocos2D physics engine has some really nice functionality to do this. Just add the following method into HelloWorldScene.m:
- (BOOL)ccPhysicsCollisionBegin:(CCPhysicsCollisionPair *)pair monsterCollision:(CCNode *)monster projectileCollision:(CCNode *)projectile { [monster removeFromParent]; [projectile removeFromParent]; return YES; }
That snippet of code is pretty powerful. When the physics simulation is set up, the physics engine will check for CCPhysicsCollisionDelegate
methods and call them if they exist. The parameter names will be taken to be the collisionTypes you want to deal with yourself.
In this method you are completely removing both the ‘projectile’ and ‘monster’ nodes from the simulation and scene. You could of course add a score counter, apply a special effect or anything else you would like to do each time a projectile collides with monster.
Build and run and you finally should be able to destroy those monsters. Go go power ninja!
You’re 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, it’s all good to go.
History Lesson: For the Cocos2D historians out there wondering what happened to SimpleAudioEngine, that sound 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% accurate representation of a ninja throwing a shuriken :-)
Add the following to the end of your projectile creating touchBegan:
method.
[[OALSimpleAudio sharedInstance] playEffect:@"pew-pew-lei.caf"];
Time to add a little mood music, add this line to init
, right after setting userInteractionEnabled
toYES
:
[[OALSimpleAudio sharedInstance] playBg:@"background-music-aac.caf" loop:YES];
As a final step, comment out this line in init
to turn off debug drawing:
_physicsWorld.debugDraw = YES;
Build and run, pew-pew. You now have sound, how easy was that?
And that’s a wrap! Here’s the full code for the Cocos2D 3.0 game that 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 IntroScene you will see how to create a label. Why not try adding a counter to your 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 References and search for CCAction you will get a list of all the actions available that you can apply to any of your game character objects.
I’ve never seen a shuriken that didn’t spin, how about a little rotation (I’m sure we’ve seen an example of that earlier in this tutorial). Hint: You can use runAction
more than once on a node. It doesn’t have to be in a sequence.
If you want to learn more about Cocos2D, the official Cocos2D forum is a friendly place to ask questions and learn from years 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.raywenderlich.com/61391/how-to-make-a-simple-iphone-game-with-cocos2d-3-0-tutorial
感觉非常好的cocos2d-iPhone-3.0的入门实例教程。