Cocos2d Tips: Sounds & Text
Professionalize your game by adding sounds and text for menus and labels throughout your game.
SOUND
To play sounds you need the Sound Engine, which you import into your layer like so:
#import “SimpleAudioEngine.h”
Then you can just code a method to handle some background music playing:
-(void)loadAudio {
// Loading Sounds Synchronously
[CDSoundEngine setMixerSampleRate:CD_SAMPLE_RATE_MID];
[[CDAudioManager sharedManager] setResignBehavior:kAMRBStopPlay
autoHandle:YES];
soundEngine = [SimpleAudioEngine sharedEngine];
[soundEngine preloadBackgroundMusic:BACKGROUND_MUSIC];
[soundEngine playBackgroundMusic:BACKGROUND_MUSIC];
}
You can see immediately that you can preload the audio in one place and then play it in another. This is great for game performance. This means you can preload audio in the main menu, for example, and then play it when you actually need it.
Another way to put this into perspective is to preload an audio when an object such as an enemy ship or main player is created and then play the specific sound when his state is changed. For example, if you create a main player class which manage the player’s state between walking, jumping, running, flying…you can make the calls to play different sound effects when the player’s state changes.
For example;
-(void)changeState:(CharacterStates)newState {
// stop all, nil action, nil move, newPosition ivar, set new state passed into it…
[self stopAllActions];
id action = nil;
[self setCharacterState:newState];
switch (newState) {
case kStateFlying:
action = [CCAnimate actionWithAnimation:flyingAnim];
break;
default:
break;
} // ends the switch that checks for state
if (action != nil) {
[self runAction:[CCRepeatForever actionWithAction:action]];
}
}
You can also get more sophisticated and preload audio into your layer using plists for lists of files which are loaded as soon as the scene is loaded. We will look at this in the Advanced flavor of this post!
TEXT
Now let’s move on to some text. One of my favorite places to add text is at the beginning of a layer when the game is about to start. For this we create a label like so:
CGSize winSize = [CCDirector sharedDirector].winSize;
label = [CCLabelTTF labelWithString:@"hello!" dimensions:CGSizeMake(300, 250) hAlignment:UITextAlignmentCenter fontName:@"Stencil" fontSize:40];
label.color = ccc3(000,000,000);
label.position = ccp(winSize.width/2, winSize.height/2);
This creates a simple label which you can place anywhere on the screen, change its color etc. Let’s say you also wanted to animate this label, you could string this along at the bottom:
CCScaleTo *scaleUp = [CCScaleTo actionWithDuration:2.5 scale:1.8];
CCScaleTo *scaleBack = [CCScaleTo actionWithDuration:0.5 scale:1.5];
CCDelayTime *delay = [CCDelayTime actionWithDuration:3.0];
CCFadeOut *fade = [CCFadeOut actionWithDuration:1.5];
CCHide *hide = [CCHide action];
CCSequence *sequence = [CCSequence actions:scaleUp, scaleBack, delay, fade, hide, nil];
[label runAction:sequence];
Cool! Now you’ve got the workings of some awesome eye candy for your games.
GrandCentralDispatch & Blocks
GCD helps improve your apps performance and responsiveness by outsourcing processes that require a lot or computing power to the background while keeping your UI responsive. Normally you might want to do some heavy lifting.
Let's create an Empty Application. You need to declare a IBOutlet UIImageView *imageView ivar in your appDelegate, make it a property and synthesize it in .m and make the connection in Interface Builder, IB.
Cocos2d Tips: Design Game Objects for your game
Keep your game classes organized and logically ordered. Create a GameObject class, a GameCharacter class and then subclass these.
Its important to keep your Game Objects ordered as well as your code. The more you order your objects, the cleaner your code will be as well. A GameObject is anything used in a game from labels to sprites to power ups.
Its important to create a base class for all objects because, as a simple example, you want to be able to constrain all game objects to your screen. Its not unthinkable to believe that at some point you might inadvertently cause a game object to be pushed off screen. Thus it would be nice to have a method, something like keepObjectInBounds, to make sure you can call it on any or all objects to make sure they are not halfway or all the way offscreen.
After you build you base class, GameObject, you will subclass it to build objects. But you can also subclass GameObject to build functionally similar types of objects like a Powerups subclass or an Enemy subclass. For example, you might want all Powerup class objects to have a setAutoDestroyTime method that gives any object of that class a specific time to live onscreen before it disappears.
So let’s look at init methods, designated initializers, self and super.
You can create a GameObject Class in 1 file set or in different file sets. This is where self and super take hold in your brain. Self means, that very same class you are currently in. Super means its super or parent class. For example, lets say we create this hierarchy:
- GameObject (Everything is a GameObject)
- GameCharacter (Distinguish between GameCharacters and GamePowerUps)
- GameEnemy (Some GameCharacters are bad and some are good)
- GameBigBossEnemy
- GamePlayer
- GamePlayerHero
- GamePlayerFriend
- GameEnemy (Some GameCharacters are bad and some are good)
- GamePowerup
- GameCharacter (Distinguish between GameCharacters and GamePowerUps)
GameCharacter is a subclass of GameObject. Which is to say, GameObject is the parent of GameCharacter. This makes sense because your GameObjects may be characters that have a personality and animation and perform actions. But some GameObjects will just sit there, like trees and clouds. Clouds may be moved by wind and that is about it! But a GamePlayer, our hero, needs to have a lot more internal logic, his own Artificial Intelligence logic if you will.
By the same token, GamePlayer may include our hero instance but it may also include a friend instance, which may be like his sidekick or something. The logic for a friend will not include any methods to follow or attach our hero, whereas enemies will have to have that sort of logic.
This is the reason we subclass objects, in order to use a base functionality for all (all game objects must remain onscreen at all times) but give specific functionality to others (followMainPlayer method).
Lets say you’re inside GamePlayerHero and you are coding away. If you say
[self blowHisNose];
You are calling the blowHisNose method which should exist in our GamePlayerHero class. If it doesn’t exist in self, that object will look to its super for a corresponding method. You don’t need to call:
[super blowHisNose];
That is what object inheritance in OOP is all about. So if the method doesn’t exist in GamePlayerHero, the hero object looks to its parent class or super class, GamePlayer. If GamePlayer doesn’t have that method then it will keep going until it finds that method. If it doesn’t, your game will crash
.
So lets take a look at a practical example, an initializer. An initializer is just another name for a Class’ init method. Every class must have an init method. Here is a typical one:
-(id) init {
if((self=[super init]);
}
return self;
}
This means, if this class is equal to super’s init, then do this and return self. Since a class will always have a super class, this basically says, if I have a super class (which is always) then return myself.
Now if a child class (lets call it GameCharacter class) of this previous class (GameObject class) wants to add functionality to its parent class, then it will NOT OVERRIDE its parent class methods, it will simply add methods. So the new GameCharacter class could just have a method like this:
-(void)checkAndClampSpritePosition {
CGPoint currentSpritePosition = [self position];
CGSize levelSize = [[GameManager sharedGameManager]
getDimensionsOfCurrentScene];
float xOffset;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
// Clamp for the iPad
xOffset = 30.0f;
} else {
// Clamp for iPhone, iPhone 4, or iPod touch
xOffset = 24.0f;
}
if (currentSpritePosition.x < xOffset) {
[self setPosition:ccp(xOffset, currentSpritePosition.y)];
} else if (currentSpritePosition.x > (levelSize.width – xOffset)) {
[self setPosition:ccp((levelSize.width - xOffset),
currentSpritePosition.y)];
}
}
Which says, Im not initializing anything (because if it does, it will erase its parent’s init method), Im just adding this method to any instance of GameCharacter AND every instance of GameCharacter will still have to be initialized from GameObject’s init.
Let’s see a more practical example. Let’s look at an Enemy Class which can generate many different kinds of instances, all from the same code:
@interface ShipTarget : CCSprite {
int _curHp;
int _minMoveDuration;
int _maxMoveDuration;
NSString *filename;
}
@property (nonatomic, assign) int hp;
@property (nonatomic, assign) int minMoveDuration;
@property (nonatomic, assign) int maxMoveDuration;
@property (nonatomic, retain) NSString *filename;
@end
@interface Asteroid : ShipTarget {
}
+(id)target;
@end
This says, Im a ShipTarget class and my instances will all be based off of CCSprite. This means all my instances will have any methods and properties of CCSprite unless I override them (create new ones). At the same time, I wish to create an Asteroid class which derives from this ShipTarget class and it will return an object by calling its class method named target. Then in its implementation you have:
@implementation ShipTarget
@synthesize hp = _curHp;
@synthesize minMoveDuration = _minMoveDuration;
@synthesize maxMoveDuration = _maxMoveDuration;
@synthesize filename;
@end
@implementation Asteroid
+ (id)target {
Asteroid *target = nil;
if ((target = [[[super alloc] initWithFile:@”Comet.png”] autorelease])) {
target.hp = 1;
target.minMoveDuration = 2;
target.maxMoveDuration = 4;
}
return target;
}
@end
Notice again, the use of self, or target. If there is such a thing returned from calling target’s super class, (target is ShipTarget class and ShipTarget’s super class is CCSprite) initWithFile… then set those properties and return it. There is such a thing as target’s super class initWithFile method. CCSprite has an initWithFile method. Don’t believe me? Then don’t, right click over initWithFile and select Jump to Definition and watch Xcode take you to CCSprite:
-(id) initWithFile:(NSString*)filename
Cocos2d Tips: Scrolling, Parallax and wider levels
Wider Levels & Scrolling
When you create a game in Cocos2d, your screen measures 960 pixels wide on iPhone4+ and 2048 on iPad. If we want him to move farther to the right then we need to make the level bigger. Normally we set:
levelSize = screenSize;
But now we basically wish to make:
levelSize = CGSizeMake(screenSize.width * 2.0f, screenSize.height); // levelSize code
What we are doing is changing our scene levelSize to 2x the screenSize.
Our level is now twice as big and we have a GameScene, which contains a GameplayLayer & a BackgroundLayer with some background image. We want to add a layer that will scroll in the opposite direction as our player moves. To do this we will need to add a method a method called adjustLayer:
-(void)adjustLayer {
Player *player = (Player*)[sceneSpriteBatchNode getChildByTag:kPlayerSpriteTagValue];
float playerXPosition = player.position.x;
CGSize screenSize = [[CCDirector sharedDirector] winSize];
float halfOfTheScreen = screenSize.width/2.0f;
CGSize levelSize = [[GameManager sharedGameManager] getDimensionsOfCurrentScene];//1
if ((playerXPosition > halfOfTheScreen) && (playerXPosition < (levelSize.width – halfOfTheScreen))) {
// then scroll background
float newXPosition = halfOfTheScreen – playerXPosition;
[self setPosition:ccp(newXPosition,self.position.y)]; // 2 self is the game layer
}
}
Here comment //1 is a call to a method which returns the desired levelSize. Or you can simply hard code it in this case by replacing this line with the //levelSize code line from above. Remember we are running this method in the GameplayLayer, which is self in this code. This needs to be called constantly so you must add this line to your update layer. What we are doing here is keeping the screen centered on the player. Now in the update method add this code:
//1. Get the list of objects on the layer & loop through them
CCArray *listOfGameObjects = [sceneSpriteBatchNode children];
for (GameCharacter *tempChar in listOfGameObjects) {
[tempChar updateStateWithDeltaTime:dt andListOfGameObjects:listOfGameObjects];
}
//2. Call the adjustLayer method
[self adjustLayer];
Perfect! Now let’s add the image that is actually going to scroll. Add this method to your GameplayLayer.m:
-(void)addScrollingBackground {
CGSize screenSize = [[CCDirector sharedDirector] winSize];
CGSize levelSize = [[GameManager sharedGameManager] getDimensionsOfCurrentScene];
CCSprite *scrollingBackground;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
// Indicates game is running on iPad
scrollingBackground = [CCSprite spriteWithFile:@"mars_landscape2x.png"];
} else {
scrollingBackground = [CCSprite spriteWithFile:@"mars_landscape2x.png"];
}
[scrollingBackground setPosition:ccp(levelSize.width/2.0f,screenSize.height/2.0f)];
[self addChild:scrollingBackground z:1];
}
In order for this to appear, we need to call it from the init method by adding this line:
[self addScrollingBackground];
Let’s review. addScrollingBackground adds a new image to the GameplayLayer. (This image is positioned over the true background, which is in the BackgroundLayer.) Therefore, the new image you add here should be a sort of rocky ground floor that will slide sideways as the player moves.
Make sure the image is twice as big as the screen so there will be enough of it to scroll through as the player moves.
Now Build & Run and watch your ground scroll differently as your background as your player moves left or right.
Parallax
Parallax makes one layer scroll faster or slower than the other. It’s quite easy to achieve this effect. First add a new instance variable to your GameplayLayer.m file like so:
@implementation GameplayLayer {
CCParallaxNode *parallaxNode;
}
NOTE: We are extending the @implementation line to include an ivar. No need to declare it in the @interface file. Remember .h files (header files) only need to include what properties or methods you want your object to expose to other calling objects.
And now replace your addScrollingBackground method with this one:
// Scrolling 3 Parallax backgrounds
-(void)addScrollingBackgroundWithParallax {
CGSize screenSize = [[CCDirector sharedDirector] winSize];
CGSize levelSize = [[GameManager sharedGameManager]
getDimensionsOfCurrentScene];
CCSprite *BGLayer1;
CCSprite *BGLayer2;
CCSprite *BGLayer3;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
// Indicates game is running on iPad
BGLayer1 = [CCSprite spriteWithFile:@"mars_landscape2x.png"];
BGLayer2 = [CCSprite spriteWithFile:@"some_rocks.png"];
BGLayer3 = [CCSprite spriteWithFile:@"some_pillars.png"];
} else {
BGLayer1 = [CCSprite spriteWithFile:@" mars_landscape2x.png"];
BGLayer2 = [CCSprite spriteWithFile:@" some_rocks.png"];
BGLayer3 = [CCSprite spriteWithFile:@" some_pillars.png"];
}
parallaxNode = [CCParallaxNode node];
[parallaxNode setPosition:ccp(levelSize.width/2.0f,screenSize.height/2.0f)];
float xOffset = 0;
// Ground moves at ratio 1,1
[parallaxNode addChild:BGLayer1 z:40 parallaxRatio:ccp(1.0f,1.0f) positionOffset:ccp(0.0f,0.0f)];
xOffset = (levelSize.width/2) * 0.3f;
[parallaxNode addChild:BGLayer2 z:20 parallaxRatio:ccp(0.2f,1.0f) positionOffset:ccp(xOffset, 0)];
xOffset = (levelSize.width/2) * 0.8f;
[parallaxNode addChild:BGLayer3 z:30 parallaxRatio:ccp(0.7f,1.0f) positionOffset:ccp(xOffset, 0)];
[self addChild:parallaxNode z:10];
}
Don’t forget to change the GameplayLayer’s init method call to:
[self addScrollingBackgroundWithParallax];
What we are doing now is adding more layers and offsetting their center positions. Thus when they move, they will move at different rates. Build & run the app.
You can use scrolling to add clouds or stars or alien birds to make some eyecandy for your users. If you choose to scroll many objects on the screen though, you might want to look into reusing them. This is a very popular technique used to improve performance of a game. You create one instance of the object at a time and add it to an array for tracking. When that instance moves offscreen, you remove it from that array. This saves you a lot of memory.
How Cocos2d taught me iOS and OOP
I started studying iOS in 2009, started studying Cocos2d in 2011. I never understood how to do things in code for iOS. It was all a big mystery to me.
What do you mean create a button programmatically and add it to the subview and position it and change its attributes? I can just drag one from the Object Library onto the canvas and put it wherever I want and change its color etc…
After a year of using Cocos2d, I know cherish its teachings as I find myself trying to make an app which requires objects such as UIPageControl and UIScrollView and UIImageViews with UIImages. In doing this you run into the situation of:
How do I position a view, or rather a bunch of UIImageViews that are not on the canvas but will be when the UIPageControl’s value changes!?
EPIPHANY!
Cool Image Transparency Gradient Effect
So the other day I was trying to figure out how to do something in Pixelmator (Im pretty sure it works for Photoshop) and I accidentally stumbled into this effect.
First, I opened up an image that I wanted to spruce up.
Second, I Added a Layer Mask in the Layer Menu
Then, I used a Transparent to Black Gradient and got this:
Why is this cool? Well, now you can add a nice background color or even another image in the background to make some very professional looking artwork!
The original idea I was after was from a tutorial I found online which took a picture, such as this one. You take a picture such as this:
Add a Layer Mask as before but this time choose Brush 100 with a black foreground color. Eliminate everything around her by painting with the brush to get this:
Cute huh!
Now create a new layer and Add a Gradient, preferrably one with 2 pastel colors and move it over this one:
Finally change Blending to Screen and voila!
Give a man an app … but teach a man to c
Give a man an app … but teach a man to code … #iOS #ObjC http://ow.ly/i4FbH








