4. 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
Thursday, June 21, 12
10. And most importantly..
Tons of great features for games
SceneTransitionsSprite Sheets
Effects:
Lense, Ripple,Wave..
Actions:
Move, Rotate, Scale..
Integrated Physics Engines
Sound Support
Tile Map Support
Text RenderingParticle Systems
Parallax Scrolling
Shaders (v2.0)Ribbons
Thursday, June 21, 12
16. Director & Scenes
Intro Main Menu Level I Level 2 Victory
Options
High Scores
LossDirector
â Game made up of âgame screensâ called Scenes
â Each Scene can be considered a separate app
â Director handles main window and executes Scenes
Thursday, June 21, 12
17. Layers
â Each Scene contains several full screen Layers
â Layers contain Sprites which are the game elements
â Layers useful for Controls, Background, Labels, Menus.
Thursday, June 21, 12
18. 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
Thursday, June 21, 12
19. Sprites in Action
Create
CCSpriteFrame* spriteFrame = [[CCSpriteFrameCache sharedSpriteFrameCache]
spriteFrameByName:@"sprite.png"];
CCSprite* sprite = [CCSprite spriteWithSpriteFrame:spriteFrame];
Thursday, June 21, 12
20. Sprites in Action
Add to Layer
sprite.position = ccp(x, y);
[layer addChild:sprite z:5 tag:666];
(0,0)
winSize.height
winSize.width
(x,y) at anchor point
Thursday, June 21, 12
21. Sprites in Action
Move
CCMoveTo *moveToAction = [CCMoveTo actionWithDuration:duration
position:newPosition];
[sprite runAction:moveToAction];
Properties can be transformed directly or through actions
Thursday, June 21, 12
24. Sprites in Action
Schedule Updates
[scene schedule:@selector(updateSprite:) interval:interval];
Thursday, June 21, 12
25. Actions
Can be performed on Sprites or any Node
Basic Move, Scale, Rotate, Bezier, Hide, Fade,Tint..
Composition Sequence, Repeat, Spawn, RepeatForever..
Ease Ease, EaseExponential, EaseBounce..
Effects Lens, Liquid, Ripple, Shaky,Twirl,Waves..
Special CallFunc, Follow..
Thursday, June 21, 12
26. Spritesheets
â Added as a child to the layer
â Created withTexturePacker or Zwoptex
â Memory considerations, 16bit images, .pvr.ccz
Thursday, June 21, 12
27. Controls
â Implement directly based on CCStandardTouchDelegate
â Can use UIGestureRecognizer classes
â Open source implementations of joypad/buttons available
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
Thursday, June 21, 12
32. Music & SFX
Explosive Attack by McTricky @ Sakari InïŹnity
http://www.sakari-inïŹnity.net/author/McTricky
Background music, shoot sound, death sound
Thursday, June 21, 12
33. Music & SFX
Explosive Attack by McTricky @ Sakari InïŹnity
http://www.sakari-inïŹnity.net/author/McTricky
Background music, shoot sound, death sound
Thursday, June 21, 12
37. @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;
}
HelloWorldScene.h
Thursday, June 21, 12
38. 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;
}
Thursday, June 21, 12
45. Step 3:Adding Bad Guys (Game Logic)
(in init)
[self schedule:@selector(addTarget:) interval:1.0f];
Schedule a new target every second
Thursday, June 21, 12
46. // Create a new enemy
-(void)addTarget:(ccTime)dt {
// Create the target sprite
CCSpriteFrame *targetFrame = [[CCSpriteFrameCache sharedSpriteFrameCache]
spriteFrameByName:@"target.png"];
!CCSprite *target = [CCSprite spriteWithSpriteFrame:targetFrame];
// Add the target to the layer and the array
! [self addChild:target];
! [_targets addObject:target];
Step 3:Adding Bad Guys (Game Logic)
Create a sprite for the target
Thursday, June 21, 12
47. Step 3:Adding Bad Guys (Game Logic)
! // Determine where to spawn the target along the X axis
! CGSize winSize = [[CCDirector sharedDirector] winSize];
// Find a random X for the target in the right half of the screen
! int minX = winSize.width/2;
! int maxX = winSize.width - target.contentSize.width;
! int rangeX = maxX - minX;
! int actualX = (arc4random() % rangeX) + minX;
target.position = ccp(actualX, 320);
target.anchorPoint = ccp(0, 0);
! // Determine speed of the target
! int minDuration = 2.0;
! int maxDuration = 4.0;
! int rangeDuration = maxDuration - minDuration;
! int actualDuration = (arc4random() % rangeDuration) + minDuration;
Generate a random x position for the target
Thursday, June 21, 12
48. Step 3:Adding Bad Guys (Game Logic)
// Create and run the actions
CCMoveTo* moveTarget = [CCMoveTo actionWithDuration:actualDuration
! ! ! position:ccp(actualX, -target.contentSize.height/2)];
CCCallFuncN* actionForTargetMoveDidFinish = [CCCallFuncN
actionWithTarget:self selector:@selector(targetMoveFinished:)];
[target runAction:[CCSequence actions:moveTarget, actionForTargetMoveDidFinish, nil]];
Create a move action for the target with a
callback when reaching the bottom
Thursday, June 21, 12
49. Step 3:Adding Bad Guys (Game Logic)
// 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];
}
Add the callback method for a target that
dies or reaches the bottom
Thursday, June 21, 12
54. Step 5: Check for Bad Guy Death
-(void)update:(ccTime)dt {
CCSprite* bulletToRemove = nil;
for (CCSprite *bullet in _bullets) {
for (CCSprite* target in _targets) {
CGRect targetBox = 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:bulletToRemove cleanup:YES];
[_bullets removeObject:bulletToRemove];
}
}
Thursday, June 21, 12
55. Step 5: Check for Bad Guy Death
Thursday, June 21, 12
56. Step 6:Animating Our Hero
(In init)
// Load the animation for player
NSMutableArray *animFrames1 = [NSMutableArray array];
for (int i = 1; i < 12; i++) {
CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:
[NSString stringWithFormat:@"player_%02d.png",i]];
! [animFrames1 addObject:frame];
}
[[CCAnimationCache sharedAnimationCache] addAnimation:[CCAnimation
animationWithFrames:animFrames1 delay:FRAME_DELAY] name:@"player"];!
Preload the animation from the spritesheet
Thursday, June 21, 12
57. Step 6:Animating Our Hero
(In ccTouchesEnded)
// Actions for shooting animation
CCCallFunc* actionForShootDidEnd = [CCCallFunc actionWithTarget:self
selector:@selector(shootDidEnd)];
CCAnimation* playerShootAnimation = [[CCAnimationCache sharedAnimationCache]
animationByName:@"player"];
CCAnimate* shootAnimate = [CCAnimate actionWithAnimation:playerShootAnimation];
[_player runAction:[CCSequence actionOne:shootAnimate two:actionForShootDidEnd]];
Animate the hero when shooting
Thursday, June 21, 12
63. Step 9:Adding Sound & Music
(In init)
! // Start background music, set lower volume
! SimpleAudioEngine.sharedEngine.backgroundMusicVolume = 0.4f;
! [[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"explosive_attack.mp3"];
(In ccTouchesEnded)
! // Play sound effect on every shot and on death
! [[SimpleAudioEngine sharedEngine] playEffect:@"shot.wav"];
! [[SimpleAudioEngine sharedEngine] playEffect:@"death.wav"];
Thursday, June 21, 12
66. Para-Shoot 2.0
Enemies can move and attack
Joypad + HUD
Move our hero
Different weapons, power ups and health
Game menu and high scores
Levels
Save/Load Game
Refactor code (More scenes and layers)
Thursday, June 21, 12
67. Refactoring Para-Shoot
Intro Main Menu Level X Victory
Options
High Score
Loss
Level X Background Player Bad Guys Joypad/HUD
Scenes:
Layers:
Thursday, June 21, 12
68. More stuff to explore
â Physics Engines - Chipmunk and Box2D
â Particle System
â Tilemaps
â Menu Interface
Thursday, June 21, 12
69. 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
SapusTongue Source Code: http://www.sapusmedia.com/sources
Thursday, June 21, 12