ios game development with cocos2d

70
iOS Game Development with Cocos2D Yaron Karasik [email protected] @Greenwell Thursday, June 21, 12

Upload: greenwell

Post on 08-May-2015

18.951 views

Category:

Technology


4 download

DESCRIPTION

Cocos2D is an extensive and popular framework for developing games for iOS devices. In this talk we'll explore iOS app development and Cocos2D, and build a game using the framework.

TRANSCRIPT

Page 1: iOS Game Development with Cocos2D

iOS Game Developmentwith Cocos2D

Yaron [email protected] @Greenwell

Thursday, June 21, 12

Page 2: iOS Game Development with Cocos2D

iOS Game Developmentwith Cocos2D

Part 1: Why Cocos2D?

Part 2: Cocos2D Basics

Part 3: Let’s build a Cocos2D game

Thursday, June 21, 12

Page 3: iOS Game Development with Cocos2D

Part 1: Why Cocos2D?

Thursday, June 21, 12

Page 4: iOS Game Development with Cocos2D

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

Page 5: iOS Game Development with Cocos2D

The Cocos2D Family

Cocos2d-Android (Java)

Cocos2d-XiPhone/Android (C++)

Cocos2d-Mac (Obj-C)

Cocos2d-XNAWindows Phone 7 (C#)

Cocos2d-HTML5Web (Javascript)

Cocos3D (Obj-C)

Thursday, June 21, 12

Page 6: iOS Game Development with Cocos2D

Proven Success

Thursday, June 21, 12

Page 7: iOS Game Development with Cocos2D

Great Effort-Flexibility Balance

0

100

Effort

Flexibility

Cocos2D/Sparrow

Unity/Corona

Direct OpenGL/CoreGraphics

Thursday, June 21, 12

Page 8: iOS Game Development with Cocos2D

Cross Device, Cross Resolution

Thursday, June 21, 12

Page 9: iOS Game Development with Cocos2D

Active Ecosystem

Thursday, June 21, 12

Page 10: iOS Game Development with Cocos2D

And most importantly..Tons of great features for games

Scene TransitionsSprite 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

Page 11: iOS Game Development with Cocos2D

Part 2: Cocos2D Basics

Thursday, June 21, 12

Page 12: iOS Game Development with Cocos2D

Basic Cocos2D Concepts

Director

Thursday, June 21, 12

Page 13: iOS Game Development with Cocos2D

Basic Cocos2D Concepts

Director

Scenes

Thursday, June 21, 12

Page 14: iOS Game Development with Cocos2D

Basic Cocos2D Concepts

Director

Scenes

Layers

Thursday, June 21, 12

Page 15: iOS Game Development with Cocos2D

Basic Cocos2D Concepts

Director

Scenes

Layers

Sprites

Thursday, June 21, 12

Page 16: iOS Game Development with Cocos2D

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

Page 17: iOS Game Development with Cocos2D

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

Page 18: iOS Game Development with Cocos2D

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

Page 19: iOS Game Development with Cocos2D

Sprites in Action

Create

CCSpriteFrame* spriteFrame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"sprite.png"]; CCSprite* sprite = [CCSprite spriteWithSpriteFrame:spriteFrame];

Thursday, June 21, 12

Page 20: iOS Game Development with Cocos2D

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

Page 21: iOS Game Development with Cocos2D

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

Page 22: iOS Game Development with Cocos2D

Sprites in Action

Scale/Rotate

CCScaleTo *scaleToAction = [CCScaleTo actionWithDuration:duration scale:scale];CCRotateBy *rotateByAction = [CCRotateBy actionWithDuration:duration angle:angle];

CCSequence *sequence = [CCSequence actions:scaleToAction, rotateByAction, nil]; [sprite runAction:sequence];

Thursday, June 21, 12

Page 23: iOS Game Development with Cocos2D

Sprites in Action

Animate

CCAnimation* animation = [[CCAnimationCache sharedAnimationCache] animationByName:@"animation"];CCAnimate* animateAction = [CCAnimate actionWithAnimation:animation]; [sprite runAction:animateAction];

Thursday, June 21, 12

Page 24: iOS Game Development with Cocos2D

Sprites in Action

Schedule Updates

[scene schedule:@selector(updateSprite:) interval:interval];

Thursday, June 21, 12

Page 25: iOS Game Development with Cocos2D

ActionsCan 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

Page 26: iOS Game Development with Cocos2D

Spritesheets

★ Added as a child to the layer★ Created with TexturePacker or Zwoptex★ Memory considerations, 16bit images, .pvr.ccz

Thursday, June 21, 12

Page 27: iOS Game Development with Cocos2D

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

Page 28: iOS Game Development with Cocos2D

Let’s Make a Game!Part 3:

Thursday, June 21, 12

Page 29: iOS Game Development with Cocos2D

Let’s Make a Game!..but first we need a story, graphics, music and sfx :)

Part 3:

Thursday, June 21, 12

Page 30: iOS Game Development with Cocos2D

Because he likes to kill paratroopers

Para-Shoot

Thursday, June 21, 12

Page 31: iOS Game Development with Cocos2D

Graphics

Benjamin Radchek Sprites by The_Protoganist and _Allen_

http://www.freewebs.com/teh_pro/sprites.htm

Thursday, June 21, 12

Page 32: iOS Game Development with Cocos2D

Music & SFX

Explosive Attack by McTricky @ Sakari Infinity

http://www.sakari-infinity.net/author/McTricky

Background music, shoot sound, death sound

Thursday, June 21, 12

Page 33: iOS Game Development with Cocos2D

Music & SFX

Explosive Attack by McTricky @ Sakari Infinity

http://www.sakari-infinity.net/author/McTricky

Background music, shoot sound, death sound

Thursday, June 21, 12

Page 34: iOS Game Development with Cocos2D

Sneak Peek

Thursday, June 21, 12

Page 35: iOS Game Development with Cocos2D

Steps for making Para-ShootApplication Setup

Step 1: Adding Background

Step 2: Adding Our Hero

Step 3: Adding Bad Guys (Game Logic)

Step 4: Killing Bad Guys (Adding UI)

Step 5: Check for Bad Guy Death

Step 6: Animating Our Hero

Step 7: Animating Bad Guys Dying

Step 8: Adding Body Count

Step 9: Adding Sound & Music

Thursday, June 21, 12

Page 36: iOS Game Development with Cocos2D

New Cocos2D Project

Thursday, June 21, 12

Page 37: iOS Game Development with Cocos2D

@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

Page 38: iOS Game Development with Cocos2D

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

Page 39: iOS Game Development with Cocos2D

Hello World

Thursday, June 21, 12

Page 40: iOS Game Development with Cocos2D

Step 1: Adding Background

(In init)

// Get the window size to place elementsCGSize winSize = [[CCDirector sharedDirector] winSize]; // Add the background imageCCSprite *background = [CCSprite spriteWithFile:@"background.png"];background.position = ccp(winSize.width/2, winSize.height/2);[self addChild:background z:0];

Thursday, June 21, 12

Page 41: iOS Game Development with Cocos2D

Step 1: Adding Background

Thursday, June 21, 12

Page 42: iOS Game Development with Cocos2D

Step 2: Adding Our Hero

(In init)// Load the sprite sheetCCSpriteBatchNode *batchNode = [CCSpriteBatchNode batchNodeWithFile:@"parashoot.pvr.ccz"];[self addChild:batchNode]; // Load the sprites into the shareSpriteFrameCache[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"parashoot.plist"];

Preload the spritesheet

Thursday, June 21, 12

Page 43: iOS Game Development with Cocos2D

Step 2: Adding Our Hero

// Add the player spriteCCSpriteFrame* playerFrame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"player_01.png"];

_player = [CCSprite spriteWithSpriteFrame:playerFrame];_player.position = ccp(_player.contentSize.width/2 + 10, winSize.height/2);

[self addChild:_player z:1];

Add the hero sprite

Thursday, June 21, 12

Page 44: iOS Game Development with Cocos2D

Step 2: Adding Our Hero

Thursday, June 21, 12

Page 45: iOS Game Development with Cocos2D

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

Page 46: iOS Game Development with Cocos2D

// 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

Page 47: iOS Game Development with Cocos2D

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

Page 48: iOS Game Development with Cocos2D

Step 3: Adding Bad Guys (Game Logic)

// Create and run the actionsCCMoveTo* 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

Page 49: iOS Game Development with Cocos2D

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

Page 50: iOS Game Development with Cocos2D

Step 3: Adding Bad Guys (Game Logic)

Thursday, June 21, 12

Page 51: iOS Game Development with Cocos2D

Step 4: Killing Bad Guys (Adding UI)

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {! // Choose one of the touches to work with! UITouch *touch = [touches anyObject];! CGPoint location = [touch locationInView:[touch view]];! location = [[CCDirector sharedDirector] convertToGL:location];! if (!_isShooting) { _isShooting = YES;

Detect the touch

Thursday, June 21, 12

Page 52: iOS Game Development with Cocos2D

Step 4: Killing Bad Guys (Adding UI)

// Create the bullet CCSpriteFrame* bulletFrame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"bullet.png"];CCSprite* bulletSprite = [CCSprite spriteWithSpriteFrame:bulletFrame];bulletSprite.position = _player.position;

// Bullet actions CCCallFuncN* actionForRemoveBullet = [CCCallFuncN actionWithTarget:self selector:@selector(removeBullet:)]; CCMoveBy* bulletMoveBy = [CCMoveBy actionWithDuration:1.0f position:ccp(winSize.width, 0)];[bulletSprite runAction:[CCSequence actionOne:bulletMoveBy two:actionForRemoveBullet]];

// Add bullet to layer and array[self addChild:bulletSprite];[_bullets addObject:bulletSprite];

Create the bullet

Thursday, June 21, 12

Page 53: iOS Game Development with Cocos2D

Step 4: Killing Bad Guys (Adding UI)

Thursday, June 21, 12

Page 54: iOS Game Development with Cocos2D

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

Page 55: iOS Game Development with Cocos2D

Step 5: Check for Bad Guy Death

Thursday, June 21, 12

Page 56: iOS Game Development with Cocos2D

Step 6: Animating Our Hero

(In init)

// Load the animation for playerNSMutableArray *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

Page 57: iOS Game Development with Cocos2D

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

Page 58: iOS Game Development with Cocos2D

Step 6: Animating Our Hero

Thursday, June 21, 12

Page 59: iOS Game Development with Cocos2D

Step 7: Animating Bad Guys Dying

(in update)

// Set up actions for animation and target removalCCCallFuncN* actionForDeathDidFinish = [CCCallFuncN actionWithTarget:self selector:@selector(targetMoveFinished:)];

CCAnimate* deathAnimation = [CCAnimate actionWithAnimation:[[CCAnimationCache sharedAnimationCache] animationByName:@"death"] restoreOriginalFrame:NO];

[target runAction:[CCSequence actionOne:deathAnimation two:actionForDeathDidFinish]];

Thursday, June 21, 12

Page 60: iOS Game Development with Cocos2D

Step 7: Animating Bad Guys Dying

Thursday, June 21, 12

Page 61: iOS Game Development with Cocos2D

Step 8: Adding Body Count

(In init)

NSString* bodyCountString = [NSString stringWithFormat:@"%d", _bodyCount];_labelCount = [CCLabelTTF labelWithString:bodyCountString fontName:@"Arial"

fontSize:16];_labelCount.color = ccc3(0,0,0);_labelCount.position = ccp(110, winSize.height - 16);[self addChild:_labelCount z:2];

(In ccTouchesEnded)

_bodyCount++;NSString* bodyCountString = [NSString stringWithFormat:@"%d", _bodyCount];![_labelCount setString:bodyCountString];

Thursday, June 21, 12

Page 62: iOS Game Development with Cocos2D

Step 8: Adding Body Count

Thursday, June 21, 12

Page 63: iOS Game Development with Cocos2D

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

Page 64: iOS Game Development with Cocos2D

Step 9: Adding Sound & Music

Thursday, June 21, 12

Page 65: iOS Game Development with Cocos2D

Let’s Play!

Thursday, June 21, 12

Page 66: iOS Game Development with Cocos2D

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

Page 67: iOS Game Development with Cocos2D

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

Page 68: iOS Game Development with Cocos2D

More stuff to explore

★ Physics Engines - Chipmunk and Box2D

★ Particle System

★ Tilemaps

★ Menu Interface

Thursday, June 21, 12

Page 69: iOS Game Development with Cocos2D

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/sources

Thursday, June 21, 12

Page 70: iOS Game Development with Cocos2D

Thank You!Yaron Karasik

[email protected]

@Greenwell

Thursday, June 21, 12