It is always better to add a pause button to your game so that if the player receives a call, he/she can pause the game and resume it later on.
Import pauseBtnOFF.png
and pauseBtnON.png
into the project directory for this section.
In the newly renamed GameplayScene.m
file, we will add the following code at the end of the init function:
//pause button CCButton *pauseBtn = [CCButton buttonWithTitle:nil spriteFrame:[CCSpriteFrame frameWithImageNamed:@"pauseBtnOFF.png"] highlightedSpriteFrame:[CCSpriteFrame frameWithImageNamed:@"pauseBtnON.png"] disabledSpriteFrame:nil]; [pauseBtn setTarget:self selector:@selector(pauseBtnPressed:)]; pauseBtn.togglesSelectedState = YES; CCLayoutBox * btnMenu; btnMenu = [[CCLayoutBox alloc] init]; btnMenu.anchorPoint = ccp(0.5f, 0.5f); btnMenu.position = CGPointMake(winSize.width - pauseBtn.contentSize.width/2, winSize.height - pauseBtn.contentSize.height/2); btnMenu.direction = CCLayoutBoxDirectionVertical; btnMenu.spacing = 10.0f; [btnMenu addChild:pauseBtn]; [self addChild:btnMenu]; } return self; }
We will create a button called pauseBtn
and assign pauseBtnON
and pauseBtnOFF
for the normal and highlighted state of the button.
The pauseBtnPressed
variable in the button function is where we will add the logic for the button later.
The button's selected state will be set to toggle
.
The button will be added to CCLayoutBox
and placed in the upper-right part of the screen. Then, btnMenu
will be added to the scene.
Next, we will add the pauseBtnPressed
function, as follows:
-(void)pauseBtnPressed:(id)sender{ CCButton *pauseBtn = (CCButton*)sender; if(pauseBtn.state == CCControlStateHighlighted){ self.paused = false; }else{ self.paused = true; } }
We will first typecast the sender to the CCButton
type and store it as a variable named pauseBtn
.
We will then take a look at the state of the button. If the state is highlighted, we will resume the game by setting the pause property of the current class to false
. Alternatively, we can set the property to true
to pause the game.
3.17.176.72