adamtong.co.uk 1/2 iphone dev, 1/2 whatever else i feel like

28Sep/110

Cocos2d Snippets – 01 Fading a CCLayer.

I haven't been posting updates, mainly because any tutorials I've had in mind are pretty huge and I'm lazy and would rather pop locust's heads or shoot people on battlefield 3 when I get home.

Every now and again, I've saved hours of time from reusing tiny snippets of code, I came across this issue a little over 6 months ago now, but yesterday this error caught me out again.

So rather than Tutorials, I think I'll try post a useful snippet every month or something.

Anyway.

Cocos2d is immensely powerful, once of the great things about it is . I find them useful mainly for creating animated HUD or menu elements.

Okay, so lets say you have a game engine, and a pause button all built, but when you press pause, you'd actually like a new menu to appear over the top of your game.

Okay, so create a CCLayer, create the method to add it to the scene, done.

CCLayer *pauseLayer = [CCLayer node];

// add some sprites, menus and other objects to the pause layer.

[self.parent addChild:pauseLayer];

The way that it just 'pops' into existence doesn't look like it's had much TLC.

We should probably add a few of those powerful actions and give it a form of 'transition' into the scene.

CCLayer *pauseLayer = [CCLayer node];

// add some sprites, menus and other objects to the pause layer.

[self.parent addChild:pauseLayer];

// Fade the layer in.
[pauseLayer runAction:[CCFadeIn actionWithDuration:1.5f]];

Great, let's give that a go... oh wait..

-[CCLayer setOpacity:]: unrecognized selector sent to instance.

This is where the snippet comes in. Make a subclass of CCLayer, and add the code below. Use your subclass for your pauseLayer.

// Set the opacity of all of our children that support it
-(void) setOpacity: (GLubyte) opacity
{
	for( CCNode *node in [self children] )
	{
		if( [node conformsToProtocol:@protocol( CCRGBAProtocol)] )
		{
			[(id<CCRGBAProtocol>) node setOpacity: opacity];
		}
	}
}

Voila! No SIGABRT, and a nice fading transition for the Layer and all of its objects.

CCColourLayer will not cause an error when asked to Fade in and out, however it's children will not fade with it using the default setOpacity: method.

Above code written for cocos2d for iPhone v1.0.1

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)


− 5 = one

No trackbacks yet.