Pages

Adding a link to Game Center From Cocos2dx

I've just been revising how I implement Game Center, which I've ignored for a while.  Here's an easy way of linking to a leaderboard from Cocos2dx.  It just uses the RootViewController to do all the work rather than adding an extra class as it's only a little bit of code.

RootViewController.h

Change the interface to make it a leaderboard delegate:


@interface RootViewController : UIViewController <GKGameCenterControllerDelegate>

RootViewController.m

Add these:
@interface RootViewController : UIViewController


- (void) showLeaderBoard {
    
    GKGameCenterViewController *gameCenterController = [[GKGameCenterViewController alloc] init];
    if (gameCenterController != NULL)
    {
        gameCenterController.gameCenterDelegate = self;
        gameCenterController.viewState = GKGameCenterViewControllerStateLeaderboards;
        [self presentViewController: gameCenterController animated: YES completion:nil];

    }

    [gameCenterController release];

}


- (void)gameCenterViewControllerDidFinish:(GKGameCenterViewController *)leaderboardController
{
    
    [self dismissViewControllerAnimated:YES completion:nil];

}

Then, to call it, you just include

    if ([GKLocalPlayer localPlayer].authenticated == YES) {
        
  
        UIViewController* rootVC =  [UIApplication sharedApplication].keyWindow.rootViewController;
        
        [rootVC showLeaderBoard];
        
    };


Don't forget to:

#import <GameKit/GameKit.h>

as well.

No comments:

Post a comment