所以我第一次使用多人游戏,我对整个 minplayer/maxplayer 选项感到困惑。当我设置 minplayer=2 和 maxplayer=4 并测试代码时,它可以很好地连接 2 个玩家,但无需等待玩家 3-4 就直接跳转到游戏场景中。在所有插槽都被填满之前,如何防止代码进入主游戏场景?如果我设置 minPlayers=maxPlayers,代码可以正常工作。我知道 match.expectedPlayerCount==0 应该在满足 minPlayers 后触发,但它根本不会等待其他玩家加入。我在这里想念什么?
GKMatchRequest * matchRequest = [[[GKMatchRequest alloc] init] autorelease];
matchRequest.minPlayers = 2;
matchRequest.maxPlayers = 4;
gameCenterManager.matchController = [[GKMatchmakerViewController alloc] initWithMatchRequest:matchRequest];
gameCenterManager.matchController.matchmakerDelegate = self;
AppDelegate * delegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
[delegate.viewController presentViewController:gameCenterManager.matchController animated:YES completion:nil];
查找匹配代码
-(void)matchmakerViewController:(GKMatchmakerViewController *)viewController didFindMatch:(GKMatch *)match
{
TXGameCenterManager *gameCenterManager = [TXGameCenterManager sharedTXGameCenterManager];
gameCenterManager.multiplayerMatch = match;
// The delegate of the match is HelloWorldLayer
gameCenterManager.multiplayerMatch.delegate = self;
AppDelegate * delegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
[delegate.viewController dismissModalViewControllerAnimated:NO];
if( match.expectedPlayerCount==0 )
{
// Launching the game without waiting for connection change messages
NSLog(@"Begin game without waiting for match connection change messages");
// Determine the host, local or remote
NSArray * playerIds = match.playerIDs;
NSLog(@"Number of players: %d", [playerIds count]);
NSLog(@"ID of player: %@", [playerIds lastObject]);
NSLog(@"I got the player ids");
[GKPlayer loadPlayersForIdentifiers:playerIds withCompletionHandler:^(NSArray *players, NSError * error)
{
//bunch of code that gets player aliases and set host player
//start match
[self schedule: @selector(StartMultiplayerGame) interval:5.];
}
更改状态代码
-(void)match:(GKMatch *)match player:(NSString *)playerID didChangeState:(GKPlayerConnectionState)state
{
NSArray * playerIds = [NSArray arrayWithObject:playerID];
switch (state)
{
case GKPlayerStateConnected:
// handle a new player connection.
NSLog(@"Player connected!");
[GKPlayer loadPlayersForIdentifiers:playerIds withCompletionHandler:^(NSArray *players, NSError * error)
{
//bunch of code that gets player aliases and set host player
if (match.expectedPlayerCount==0)
{
//start match
[self schedule: @selector(StartMultiplayerGame) interval:5.];
}
}];
break;
case GKPlayerStateDisconnected:
// a player just disconnected.
NSLog(@"Player disconnected!");
break;
}
-(void)StartMultiplayerGame
{
[[CCDirector sharedDirector] replaceScene:[HelloWorldLayer node]];
}