Cocos2d-游戏暂停
HelloWorldLayer.m:中(相当于游戏界面)
-(void)printString
{
CCLOG(@"游戏进行中。。。");
}
-(id) init
{
if( (self=[super init])) {
CCSprite* sprite=[CCSprite spriteWithFile:@"Icon.png"];
sprite.position=ccp(150, 150);
CCRotateBy* by=[CCRotateBy actionWithDuration:1 angle:60.0]; //不停旋转的sprite;
CCRepeatForever* fo=[CCRepeatForever actionWithAction:by];
[sprite runAction:fo];
[self addChild:sprite];
CCSprite* playNormal=[CCSprite spriteWithFile:@"pause.png"];
CCSprite* playSecelt=[CCSprite spriteWithFile:@"pause.png"];
playSecelt.scale=0.9f;
CCMenuItemSprite* startSprite=[CCMenuItemSprite itemFromNormalSprite:playNormal selectedSprite:playSecelt target:self selector:@selector(gamePause)];
CCMenu* menu=[CCMenu menuWithItems:startSprite,nil]; //添加一个按钮,触发游戏暂停;
menu.position=CGPointZero;
[self addChild:menu];
menu.position=ccp(380,260);
[self schedule:@selector(printString) interval:3];//预约一个方法,3秒输出一句话;
}
return self;
}
然后新建一个GamePause类(相当于游戏暂停页面)
在GamePause.h中
@interface GamePause : CCLayer {
HelloWorldLayer* currentGameLayer;
}
+(id)initWithGamePause:(HelloWorldLayer*)delegate;
-(id)initWithGamePause:(HelloWorldLayer*)delegate;
-(void)removePauseGameLayer;
-(void)enterGamePauseGameLayer;
在GamePause.m中做如下操作:
+(id)initWithGamePause:(HelloWorldLayer*)delegate
{
return [[[self alloc] initWithGamePause:delegate] autorelease];
}
-(id)initWithGamePause:(HelloWorldLayer*)delegate
{
if ((self=[super init])) {
currentGameLayer=delegate;
[self enterGamePauseGameLayer]; //进入游戏暂停界面;
CCSprite* playNormal=[CCSprite spriteWithFile:@"back.png"];
CCSprite* playSecelt=[CCSprite spriteWithFile:@"back.png"];
playSecelt.scale=0.9f;
CCMenuItemSprite* startSprite=[CCMenuItemSprite itemFromNormalSprite:playNormal selectedSprite:playSecelt target:self selector:@selector(removePauseGameLayer)];
CCMenu* menu=[CCMenu menuWithItems:startSprite,nil]; //添加一个返回游戏按钮;
menu.position=CGPointZero;
[self addChild:menu];
menu.position=ccp(380, 100);
}
return self;
}
-(void)enterGamePauseGameLayer //进入暂停界面;
{
[currentGameLayer onExit]; //游戏界面暂时推出场景;(游戏界面所有的动作和预约方法等都将暂停)
[currentGameLayer.parent addChild:self];
}
-(void)removePauseGameLayer //退出暂停界面,返回游戏;
{
[currentGameLayer onEnter];
[self.parent removeChild:self cleanup:YES]; //
}
-(void)dealloc
{
currentGameLayer=Nil; //别忘了,释放内存;
[super dealloc];
}
在HelloWorldLayer类中完成 按下游戏暂停按钮时触发的方法;
-(void)gamePause
{
[GamePause initWithGamePause:self];
}
运行程序,点击暂停按钮;你会发现,sprite停止旋转,并且停止输出字符串;这说明helloworld中的动作和预约方法都以暂停;再次点击暂停按钮,也不会有按下的状态,说明helloworldlayer的触摸事件也被屏蔽;
点击返回按钮,sprite继续旋转,并且字符串也能再次输出;游戏暂停目的达到了;
效果图:
关键就四句话:
[currentGameLayer onExit]; //游戏界面暂时退出场景;(游戏界面所有的动作和预约方法等都将暂停)
[currentGameLayer.parent addChild:self];
[currentGameLayer onEnter];
[self.parent removeChild:self cleanup:YES]; //