5. Meet Cocos2D for iPhone
Open source iOS game development framework
Developed by Ricardo Quesada, acqui-hired by
Zynga (2011)
Stable v1.1 Based on OpenGL ES 1.1
Beta v2.0 Based on OpenGL ES 2.0
3,500+ iOS games shipped
6. The Cocos2D Family
Cocos3D
(Obj-C)
Cocos2d-Android
(Java)
Cocos2d-Mac
Cocos2d-X (Obj-C)
iPhone/Android (C++)
Cocos2d-XNA Cocos2d-HTML5
Windows Phone 7 (C#) Web (Javascript)
11. And most importantly..
Tons of great features for games
Sprite Sheets Scene Transitions Parallax Scrolling
Effects: Actions:
Tile Map Support
Lense, Ripple, Wave.. Move, Rotate, Scale..
Particle Systems Integrated Physics Engines Text Rendering
Ribbons Shaders (v2.0) Sound Support
13. Basic Cocos2D Concepts
Class that creates and handle the main Window
Director and manages how and when to execute the Scenes.
14. Basic Cocos2D Concepts
Creates and handle the main Window
Director and manages how and when to execute the Scenes.
A scene (implemented with the CCScene object) is more
Scenes or less an independent piece of the app workflow. .
15. Basic Cocos2D Concepts
Creates and handle the main Window
Director and manages how and when to execute the Scenes.
A scene (implemented with the CCScene object) is more
Scenes or less an independent piece of the app workflow. .
A CCLayer has a size of the whole drawable Layers
area, and knows how to draw itself.
16. Basic Cocos2D Concepts
Creates and handle the main Window
Director and manages how and when to execute the Scenes.
A scene (implemented with the CCScene object) is more
Scenes or less an independent piece of the app workflow. .
A layer has a size of the whole drawable
Layers
area, and knows how to draw itself.
It is a 2D image that can be moved, Sprites
rotated, scaled, animated, etc.
17. Director & Scenes
Director Loss
Intro Main Menu Level I Level 2 Victory
Options
High Scores
Game made up of “game screens” called Scenes
Each Scene can be considered a separate app
Director handles main window and executes Scenes
18. Layers
Each Scene contains several full screen Layers
Layers contain Sprites which are the game elements
Layers useful for Controls, Background, Labels, Menus.
19. Nodes
Nodes are anything that gets drawn or contains
things that get drawn (= Scene, Layer, Sprite)
Can: Contain other Nodes
Schedule periodic callbacks
Execute Actions
21. Sprites in Action
winSize.height
Add to Layer
(x,y) at anchor point
winSize.width
(0,0)
sprite.position = ccp(x, y);
[layer addChild:sprite z:5 tag:666];
22. Sprites in Action
Move
CCMoveTo *moveToAction = [CCMoveToactionWithDuration:duration
position:newPosition];
[sprite runAction:moveToAction];
Properties can be transformed directly or through actions
36. HelloWorldScene.h
@interface HelloWorldLayer : CCLayer
{
// Player sprite
CCSprite *_player;
// Target and bullet sprite arrays
NSMutableArray *_targets;
NSMutableArray *_bullets;
! // Body count counter and isShooting flag
int _bodyCount;
BOOL _isShooting;
!
// For body count label
CCLabelTTF *_labelTitle;
CCLabelTTF *_labelCount;
}
37. HelloWorldScene.m
// Create the new scene including this layer
+(id) scene
{
! // Create the scene
CCScene *scene = [CCScene node];
!
! // Create the layer
HelloWorldLayer *layer = [HelloWorldLayer node];
!
! // add layer as a child to scene
! [scene addChild: layer];
!
! // return the scene
return scene;
}
44. Step 3: Adding Bad Guys (Game Logic)
Schedule a new target every second
(in init)
[self schedule:@selector(addTarget:) interval:1.0f];
45. Step 3: Adding Bad Guys (Game Logic)
Create a sprite for the target
// Create a new enemy
-(void)addTarget:(ccTime)dt {
// Create the target sprite
CCSpriteFrame *targetFrame = [[CCSpriteFrameCachesharedSpriteFrameCache]
spriteFrameByName:@"target.png”];
CCSprite *target = [CCSpritespriteWithSpriteFrame:targetFrame];
// Add the target to the layer and the array
! [self addChild:target];
! [_targets addObject:target];}
46. Step 3: Adding Bad Guys (Game Logic)
Generate a random x position for the target
// Determine where to spawn the target along the X axis
CGSizewinSize = [[CCDirectorsharedDirector] winSize];
// Find a random X for the target in the right half of the screen
intminX = winSize.width/2;
intmaxX = winSize.width - target.contentSize.width;
intrangeX = maxX - minX;
intactualX = (arc4random() % rangeX) + minX;
target. position = ccp (actualX, 320 );
target.anchorPoint = ccp(0, 0);
// Determine speed of the target
intminDuration = 2.0;
intmaxDuration = 4.0;
intrangeDuration = maxDuration - minDuration;
intactualDuration = (arc4random() % rangeDuration) + minDuration;
47. Step 3: Adding Bad Guys (Game Logic)
Create a move action for the target with a
callback when reaching the bottom
// Create and run the actions
CCMoveTo* moveTarget = [CCMoveToactionWithDuration:actualDuration
Position:ccp(actualX,-target.contentSize.height/2)];
CCCallFuncN* actionForTargetMoveDidFinish = [CCCallFuncN
actionWithTarget:selfselector:@selector(targetMoveFinished:)];
[target runAction:[CCSequenceactions:moveTarget, actionForTargetMoveDidFinish, nil]];
48. Step 3: Adding Bad Guys (Game Logic)
Add the callback method for a target that
dies or reaches the bottom
// Method for removing a target that has died or reached the
bottom
-(void)targetMoveFinished:(id)sender {
CCSprite *target = (CCSprite *)sender;
[ self removeChild :target cleanup : YES ];
[_targets removeObject:target];
}
53. Step 5: Check for Bad Guy Death
-(void)update:(ccTime)dt {
CCSprite* bulletToRemove = nil;
for (CCSprite *bullet in _bullets) {
for (CCSprite* target in _targets) {
CGRecttargetBox = CGRectMake(target.position.x, target.position.y,
[target boundingBox].size.width, [target boundingBox].size.height);
// Check if bullet is in the target's bounding box
if (CGRectContainsPoint(targetBox, bullet.position)) {
// Animate target death and remove target
bulletToRemove = bullet;
}
}
}
// Remove bullet if target was hit
if (bulletToRemove != nil) {
[self removeChild:bulletToRemovecleanup:YES];
[ _bullets removeObject :bulletToRemove];
}
}
63. Step 9: Adding Sound & Music
(In init)
! // Start background music, set lower volume
SimpleAudioEngine.sharedEngine.backgroundMusicVolume = 0.4f;
! [[SimpleAudioEnginesharedEngine] playBackgroundMusic:@"explosive_attack.mp3"];
(In ccTouchesEnded)
// Play sound effect on every shot and on death
!
[[SimpleAudioEnginesharedEngine] playEffect:@"shot.mp3"];
!(In update: where the target is killed)
! [[SimpleAudioEnginesharedEngine] playEffect:@"death.mp3"];
65. KillTime 2.0
Enemies can move and attack
Joypad
Move our hero
Different weapons, power ups and health
Game menu and high scores
Levels
Save/Load Game
Refactor code (More scenes and layers)
66. More stuff to explore
Physics Engines - Chipmunk and Box2D
Particle System
Tilemaps
Menu Interface
67. Where can you learn more
Cocos2D Demo Library (Comes with Cocos)
Wiki: http://cocos2d-iphone.org/wiki
Ray Wenderlich: http://www.raywenderlich.com
Steffen Itterheim: http://learn-cocos2d.com
Sapus Tongue Source Code: http://www.sapusmedia.com/source