Jin
Jin

Reputation: 143

Pause game when home button is pressed for iphone sdk

I wish to pause a game when the user presses the home button, however I fail to do so. Here's what I did.

  1. I declare a NSInteger variable in appdelegate called gamestate and define two constant (kGameStateRunning and kGameStatePaused) to update the variable.

  2. When viewdidload for my mainGameViewController, i set gamestate = kGameStateRunning

  3. So what I want to do here is when a user presses home button, a pauseView is added to current mainGameViewController just like what a user will see when he presses a pause button during game play which I created.

I implement it in the appdelegate function and uses it to call a pauseGame method in my viewController. The NSLog shows that home button is pressed but it does not seem to add the pause view that i created programmatically to it. Is it because it doesn't understand [self.view addSubView:pauseView] if I were to call this in appDelegate. Thank you for your help. Here's the code.

- (void)applicationWillResignActive:(UIApplication *)application {
    if (gameState == kGameStateRunning) {
        [self.viewController pauseGame];
        NSLog(@"home button pressed");
    }
    else if (gameState == kGameStatePaused) {
        NSLog(@"not running");

-(void)pauseGame{
//pause all functions
NSLog(@"pause");
[gameTimer invalidate];
[hHpointer.packageSpawningTime invalidate];

for (Package *package in hHpointer.packageArray) {
    [package.timeSinceSpawn invalidate];
}

//create the view
pauseView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 480, 320)];
[pauseView setBackgroundColor:[UIColor grayColor]];
pauseView.alpha = 0.5;
[self.view addSubview:pauseView];
    }

Upvotes: 0

Views: 4224

Answers (1)

Zebs
Zebs

Reputation: 5448

If you are calling this from the app delegate you have a pointer to a window, not a view.

As such, you should call: [self.window addSubview:pauseView];

When the app starts over make sure to implement the - (void)applicationDidBecomeActive: method.

And remove the view calling [pauseView removeFromSuperview].

I hope this helps.

Upvotes: 1

Related Questions