游戏邦在:
杂志专栏:
gamerboom.com订阅到鲜果订阅到抓虾google reader订阅到有道订阅到QQ邮箱订阅到帮看

分享Game Center多人游戏的相关制作步骤

发布时间:2011-12-13 18:02:14 Tags:,

作者:Ray Wenderlich

本文将引导你使用Cocos2D和Game Center配对系统来制作简单的双人联网游戏。

你将要制作的游戏非常简单。游戏的内容是一条狗和一个小孩赛跑,点击屏幕的速度越快,玩家获胜的可能性就越高。

教程的假设前提是你已经对Cocos2D的基本使用方法较为熟悉。如果你是Cocos2D新手,或许需要先看看站点上的其他Cocos2D相关教程。

注:如若要完全学习该教程中的内容,你必须是iOS开发计划的注册会员,这样你的应用才能够使用Game Center。而且,你至少需要1部设备(游戏邦注:以满足在模拟器和设备上各运行游戏的条件)。最后,你还需要至少两个不同的Game Center账户,用于测试游戏(游戏邦注:开发者可以免费用新邮箱注册新Game Center账户)。

开始

本教程向你展示如何将配对系统和多人联网模式添加到游戏中。

我已经准备好了某些初始代码供初学者使用,但是这些代码中不含有联网代码。

下载这些代码并运行项目,你应该可以看到以下画面:

active(from raywenderlich)

active(from raywenderlich)

游戏非常简单,获得的评论也不错。浏览这些代码,确保你能够理解其中的所有内容。

激活Game Center:概述

现在,你已经拥有了个简单且可以玩的游戏。但是游戏显得很乏味,因为你只能自己独自体验!

如果能够使用Game Center的话,游戏会更加有趣,因为你可以邀请好友跟你一起玩,或者使用配对系统寻找在线陌生人。

但是在你开始编写有关Game Center的代码前,你需要做两件事情:

1、创建并设置应用ID

2、在iTunes Connect中注册应用

让我们来分别阐述这两件事情。

创建并设置应用ID

首个步骤是创建并设置应用ID。要实现这个目标,需要先登录iOS Dev Center,随后登录iOS Provisioning Portal。

在其中选择应用ID标签,为你的应用新建应用ID,如下所示:

creat App ID(from raywenderlich)

creat App ID(from raywenderlich)

最重要的部分是Bundle Identifier,你需要将此设置为独立的串(游戏邦注:应当与教程中所示不同!)使用你所持有的域名是个较好的选择,可以避免串名称的重合。

完成后,点击“提交”。然后打开Cat Race Xcode项目,选择Resources\Info.plist,将Bundle Identifier设置成你在iOS Provisioning Portal中输入的内容,如下图所示:

value(from raywenderlich)

value(from raywenderlich)

当你在项目中期修改Bundle Identifier时,有时可能会导致Xcode出现异常,所以需要采取以下步骤:

1、删除当前位于模拟器或设备上的Cat Race游戏副本

2、如果模拟器正在运行中,退出模拟器

3、用Project\Clean清除记录

现在,你的应用已经有了应用ID。接下来,你就可以为应用注册iTunes Connect和激活Game Center。

在iTunes Connect中注册应用

下个步骤是登录iTunes Connect并为应用创建新入口。

登录iTunes Connect后,选择“管理你的应用”,然后点击左上方蓝色的“添加新应用”选项。

在你看到的首个界面中,“应用名称”栏中输入“Cat Race”,“SKU数字”栏输入“CR1”,选择你之前创建的束ID,如下图所示:

App Name(from raywenderlich)

App Name(from raywenderlich)

点击继续,接下来要为你的应用设置某些基本信息。

不要担心自己输入的数值,因为你随后可以对其进行修改,你需要的找些东西(游戏邦注:包括图标和截图)来满足iTunes Connect提出的要求。

完成后,点击“保存”,不出意外的话你应该会进入“准备上传”阶段,看到如下内容:

App Information(from raywenderlich)

App Information(from raywenderlich)

点击右上方蓝色的“管理Game Center”选项,点击蓝色的“激活”选项,点击“完成”。这样你的应用便已经激活了Game Center,你可以编写代码了!

认证本地玩家:策略

游戏设计开始后,首先你需要做的就是认证本地玩家。

你可以将此视为“玩家登陆Game Center”。如果他之前已经登录过,会看到“欢迎回来!”的界面。如果从未登录,系统会要求输入玩家姓名和密码。

认证当地的用户很简单,你只需要调用authenticateWithCompletionHandler即可。你可以随意添加一段代码,一旦用户认证就会被调用。

但是,用户还可以用另一种方法登入或登出!他可以在使用你的应用的时候转向Game Center应用,在那里登入或登出,然后转回你的应用。

所以你的应用需要知道认证状态改变的时间,通过注册“认证改变”通知可以实现这个目标。

所以,我们采用的认证玩家的战略如下:

1、创建单例对象,将所有的Game Center代码放在同一个地方。

2、单例对象创建后,用其注册“认证改变”通知。

3、游戏会调用单例对象上的方法来认证用户。

4、无论用户何时认证或登出,“认证改变”回叫信号都将被调用。

5、回叫信号将跟踪用户当前是否处在认证状态。

现在你已经知道了这个计划,接下来我们将具体实施!

认证本地用户:执行

在Cat Race Xcode项目中,选择File\New\New File,随后选择iOS\Cocoa Touch\Objective-C class,然后点击“下一步”。在“Subclass”中输入“NSObject”,点击“下一步”,将新类命名为GCHelper.m,然后点击“完成”。

将GCHelper.h替换为以下内容:

reaplace GCHelper.h(from raywenderlich)

reaplace GCHelper.h(from raywenderlich)

这样做便导入了GameKit标题文件,然后创建了有着两种数据类型的对象,一个用来跟踪游戏中心在这款设备上是否可用,另一个用来跟踪用户当前是否处于认证状态。

它还创建出某个资产,这样游戏就可以区分出游戏中心是否可用。一个静态方法可以找回该类的单例实例,另一个方法可以认证当地用户(游戏邦注:在应用开启时调用)。

接下来转向GCHelper.m,然后在@implementation中添加以下内容:

switch to GCHelper.m(from raywenderlich)

switch to GCHelper.m(from raywenderlich)

这样便形成了gameCenterAvailable资产,然后定义方法创建此类的单例实例。

应当注意的是,编写单例方法的方法有许多种,但是这是最简单的方法,因为你无需担心多线路尝试同时初始化单例。

接下来在sharedInstance方法之后添加以下方法:

add the method(from raywenderlich)

add the method(from raywenderlich)

这种方法来源于苹果的Game Kit Programming Guide。可以查看Game Kit在当前设备上是否可用。

然后再isGameCenterAvailable方法之后添加如下内容:

add the methold after isGameCenterAvailable(from raywenderlich)

add the methold after isGameCenterAvailable(from raywenderlich)

初始方法查验的是Game Center是否可用,如果确实可用,便注册“认证改变”通知。应用在尝试认证用户之前注册此等通知很重要,这样在认证完成时才会被调用。

此刻的authenticationChanged回叫信号很简单,它查验的是改变是否源于用户认证或非认证,并据此更新状态旗帜。

应当注意的是,在实践中认证或非认证时,这可能会在一行中被调用数次,因而应当确保userAuthenticated旗帜与当前状态不同,它只在发生改变时登录。

最后,在authenticationChanged方法后添加以下方法来认证当地用户:

add the method after authenticationChanged(from raywenderlich)

add the method after authenticationChanged(from raywenderlich)

这会调用之前提到的authenticateWithCompletionHandler方法来告诉Game Kit认证用户。应当注意的是,这并未通过完成处理器。因为你已经注册了“认证改变”通知,所以上述步骤就不必要了。

GCHelper现在包含了所有认证用户的必要代码,现在你要做的就是使用它!转向AppDelegate.m,进行以下修改:

switch to AppDelegate.m(from raywenderlich)

switch to AppDelegate.m(from raywenderlich)

这样便创建了单例实例(游戏邦注:注册“认证改变”回叫信号成为初始化的一部分),然后调用authenticateLocalUser方法。

最后的步骤将Game Kit架构添加到项目中。要实现这个目标,选择Groups & Files左上角的CatRace项目,选择Build Phases标签,展开“Link Binary with Libraries”选项,然后点击“+”。

选择GameKit.framework,然后点击“添加”。将类型从“必须”改为“可选”,现在你应该可以看到如下屏幕:

change the type to Optional(from raywenderlich)

change the type to Optional(from raywenderlich)

这就是我们的目标!执行并运行项目,如果你已经登录Game Center,应该可以看到以下内容:

welcome back(from raywenderlich)

welcome back(from raywenderlich)

现在你已经认证了用户,可以转向有趣的部分,比如找些人跟你一起玩游戏!

配对

目前有两种方法可以通过Game Center来找到其他人与你一起玩游戏:搜索配对或者使用内置配对用户界面。

在这个教程中,我们将使用的是内置配对用户界面。这个想法是,当你想要寻找配对时,你在GKMatchRequest对象中设置了某些参数,然后创建和呈现GKMatchmakerViewController实例。

现在让我们看看这是如何发挥作用的。首先,对GCHelper.h进行些许修改,如下所示:

a few changes to GCHelper.h(from raywenderlich)

a few changes to GCHelper.h(from raywenderlich)

这里有许多新东西,所以我们将具体解析。

1、我们定义了一个称为GCHelperDelegate的协议,用来在重要事件发生时通知其他对象,比如配对开始、结束或者从其他人处接收数据。在这款游戏中,你的Cocos2D层将执行这个协议。

2、GCHelper对象被标识为执行两个协议。第一个是配对用户界面可以在配对是否成功时通知该对象。第二个是Game Center可以在数据接收或者连接状态改变时通知对象。

3、创建某些新实例变量和资产,以此来跟踪用来呈现配对用户界面、配对参考、是否成功的视图控制器。

4、创建Cococs2D曾能够调用来寻找配对玩家的新方法。

接下来转向GCHelper.m并做出以下修改:

switch to GCHelper.m and make changes(from raywenderlich)

switch to GCHelper.m and make changes(from raywenderlich)

这个方法是供Cocos2D曾调用来寻找配对。如果Game Center不可用的话,这个方法丝毫不起作用。

初始方法设定配对还未开始,配对对象为0。它存储了视图控制器以供后用,解除了之前已经存在的视图控制器(游戏邦注:比如正在呈现的GKMatchmakerViewController)。

然后转向重要的内容。GKMatchRequest对象允许你配置你正在寻找的配对类型,比如玩家数量的最小值和最大值。在这款游戏中,我们设定最小和最大均为2个玩家。

接下来,它用指定请求创建了GKMatchmakerViewController新实例,将其委任设置给GCHelper对象,并使用视图控制器将其呈现在屏幕上。

GKMatchmakerViewController从此时起便可发挥作用,允许用户随机搜索玩家并创建游戏。目前实现后将调用某些回叫方法,因此我们需添加以下内容:

GKMatchmakerViewController(from raywendelich)

GKMatchmakerViewController(from raywendelich)

如果用户取消配对或配对出现错误,配对视图就会关闭。

但是,如果配对被找到,它就会离开配对对象,将配对委任发送给GCHelper对象,这样它就能够知晓输入数据和连接状态改变。

它还运行了一次快速检测,查看开始配对的时机是否恰当。配对对象会跟踪仍需要完成配对的玩家数量。如果这个数量是0的话,表示所有的玩家均已配对成功。

接下来,添加GKMatchDelegate回叫执行:

GKMatchDelegate callbacks (from raywenderlich)

GKMatchDelegate callbacks (from raywenderlich)

match:didReceiveData:fromPlayer会在其他玩家向你发送数据时调用。这个方法只是简单地将数据向委任推送,这样就可以执行游戏中具体的内容。

match:player:didChangState方法的作用时,当玩家连接时你需要确认是否所有的玩家均已就位,如若准备完好就可以开始比赛。假如有玩家掉线,它就会将比赛中止并通知委任。

最后两个方法是在连接发生错误时调用。在这两种方法中,如果发生错误,它们都会中止比赛并通知委任。

现在我们拥有可以配对出比赛的代码,我们将其用在HelloWorldLayer中。转向HelloWorldLayer.h并进行如下改变:

switch to HelloWorldLayer.h(from raywenderlich)

switch to HelloWorldLayer.h(from raywenderlich)

然后转向HelloWorldLayer.m,做出如下改变:

switch to HelloWorldLayer.m and make the following changes(from raywenderlich)

switch to HelloWorldLayer.m and make the following changes(from raywenderlich)

这里最重要的部分便是初始方法。它从AppDelegate处获得RootViewController,因为那是呈现配对情况的视图控制器。然后,它会调用你刚刚在GCHelper上编写的新方法,通过呈现配对视图控制器的方式来寻找比赛。

剩下的只是些随后将执行的比赛开始或结束时的小功能。

最后要说明的是,默认的Cocos2D模板并不包含供App Delegate中RootViewController使用的资产,所以你可以添加一个。转向AppDelegate.h然后添加以下内容:

@property (nonatomic, retain) RootViewController *viewController;

然后转向AppDelegate.m将其合成:

@synthesize viewController;

执行并运行应用,你应当可以看到配对视图控制器初始页面,如下图所示:

matchmaker view controller(from raywenderlich)

matchmaker view controller(from raywenderlich)

现在在另一个设备上运行应用,这样你就会看到两个应用同时运行(游戏邦注:可以用模拟器和iPhone作为两个不同的设备)。

重要的是,确保你在两个设备上使用的是不同的Game Center账户,否则无法看到效果!

在两个设备上点击“开始游戏”,过一小段时间后,配对视图控制器应当会消失,你应该会在看到如下内容:

CatRace[16440:207] Authentication changed: player authenticated.

CatRace[16440:207] Player connected!

CatRace[16440:207] Ready to start match!

这就表示你已经构建起两个设备间的比赛!你马上就可以制作出联网游戏!

横向和GKMatchmakerViewController

你或许已经注意到,默认情况下GKMatchmakerViewController会纵向显示。很显然,这看起来很不舒服,因为这款Cocos2D游戏是横向的!

幸运的是,你可以通过补丁来强迫GKMatchmakerViewController只接受横向。

为实现这个目标,点击File\New\New File,选择iOS\Cocoa Touch\Objective-C class,然后点击“下一步”。在Subclass中输入NSObject,点击“下一步”,将新类命名为“GKMatchmakerViewController-LandscapeOnly.m”,然后点击“完成”。

将GKMatchmakerViewController-LandscapeOnly.h的内容用以下内容替换:

Replace-the-contents-of-GKMatchmakerViewController-LandscapeOnly.h(from raywenderlich)

Replace-the-contents-of-GKMatchmakerViewController-LandscapeOnly.h(from raywenderlich)

然后将GKMatchmakerViewController-LandscapeOnly.m的内容替换如下:

replace the contents of GKMatchmakerViewController-LandscapeOnly.m

replace the contents of GKMatchmakerViewController-LandscapeOnly.m

执行并运行应用,视图控制器应当会横向呈现,如下图所示:

view controller(from raywenderlich)

view controller(from raywenderlich)

游戏邦注:本文发稿于2011年4月26日,所涉时间、事件和数据均以此为准。(本文为游戏邦/gamerboom.com编译,拒绝任何不保留版权的转载,如需转载请联系:游戏邦

How To Make A Simple Multiplayer Game with Game Center Tutorial: Part 1/2

Ray Wenderlich

I’m experimenting with a new way of writing tutorials – by taking suggestions by you guys!

In the sidebar to the right (scroll down a bit), you’ll find a new section where you can vote for which tutorial comes next.

In the first vote, a bunch of you guys said you wanted a tutorial about making a simple multiplayer game (88 of you to be exact!) – so here you go! :]

In this 2-part tutorial series, you’ll make a simple 2-player networked game with Cocos2D and Game Center matchmaking.

The game you’ll be working with is very simple. It’s a racing game with a dog vs. a kid – tap as fast as you can to win!

This tutorial assumes you are already familiar with the basics of using Cocos2D. If you are new to Cocos2D, you might want to check out some of the other Cocos2D tutorials on this site first.

Note: To fully get through this tutorial series, you must be a registered member of the iOS developer program so you can enable your app to use Game Center. Also, you will need at least one physical device (so that you can run one copy on the simulator and one on your device). Finally, you will need at least two different Game Center accounts for testing (don’t worry, you can create more than one for free, you just need another email address).

Ready? On your mark, get set, GO!

Getting Started

This tutorial show you how to add matchmaking and multiplayer capabilities into a simple game.

Since making the game logic itself isn’t the point of this tutorial, I’ve prepared some starter code for you that has the game without any network code.

Download the code and run the project, and you should see a screen like this:

The game is very simple and well commented – go ahead and browse through the code and make sure you understand everything.

If you guys are interested, I could do a separate tutorial sometime on how to make this game from scratch. If you would like this, please suggest this tutorial in the forums!

Enabling Game Center: Overview

At this point, you have a simple playable game, except it’s pretty boring since you’re playing all by yourself!

It would be a lot more fun to use Game Center, so you can invite friends to play with you, or use matchmaking to play with random people online.

But before you can start writing any Game Center code, you need to do two things:

Create and set an App ID

Register your app in iTunes Connect

Let’s go through each of these in turn.

Create and Set an App ID

The first step is to create and set an App ID. To do this, log onto the iOS Dev Center, and from there log onto the iOS Provisioning Portal.

From there, select the App IDs tab, and create a new App ID for your app, similar to the following (except you’ll be choosing different values):

The most important part is the Bundle Identifier – you need to set this to a unique string (so it can’t be the same as the one I used!) It’s usually good practice to use a domain name you control followed by a unique string to avoid name collisions.

Once you’re done, click Submit. Then open the Cat Race Xcode project, select Resources\Info.plist, and set your Bundle identifier to whatever you entered in the iOS Provisioning portal, as shown below (except you’ll be entering a different value):

One last thing. Xcode sometimes gets confused when you change your bundle identifier mid-project, so to make sure everything’s dandy take the following steps:

Delete any copies of Cat Race currently on your simulator or device

Quit your simulator if it’s running

Do a clean build with Project\Clean

Congrats – now you have an App ID for your app, and your app is set up to use it! Next you can register your app with iTunes Connect and enable Game Center.

Register your app in iTunes Connect

The next step is to log on to iTunes Connect and create a new entry for your app.

Once you’re logged onto iTunes Connect, select Manage Your Applications, and then click the blue “Add New App” button in the upper left.

On the first screen, enter Cat Race for the App Name, CR1 for SKU Number, and select the bundle ID you created earlier, similar to the screenshot below:

Click continue, and follow the prompts to set up some basic information about your app.

Don’t worry about the exact values to put in, since it doesn’t really matter and you can change any of this later – you just need to put something (including a dummy icon and screenshot) in to make iTunes Connect happy.

When you’re done, click Save, and if all works well you should be in the “Prepare for Upload” stage and will see a screen like this:

Click the blue “Manage Game Center” button to the upper right, click the big blue “Enable” button, and click “Done”. That’s it – Game Center is enabled for your app, and you’re ready to write some code!

By the way – inside the “Manage Game Center” section, you might have noticed some options to set up Leaderboards or Achievments.

We won’t be covering Leaderboards or Achievements in this tutorial, but if you are interested Rod and I cover this in our upcoming Cocos2D book.

Authenticate the Local Player: Strategy

When your game starts up, the first thing you need to do is authenticate the local player.

You can think of this as “logging the player into Game Center.” If he’s already logged in, it will say “Welcome back!” Otherwise, it will ask for the player’s username and password.

Authenticating the local user is easy – you just call authenticateWithCompletionHandler. You can optionally pass in a block of code that will be called once the user is authenticated.

But there’s a trick. There’s another way for the user to log in (or log out!). He can be using your app, switch to the Game Center app, log or out from there, and switch back to your app.

So your app needs to know whenever the authentication status changes. You can find out about these by registering for an “authentication changed” notification.

So, our strategy to authenticate the player will be as follows:

Create a singleton object to keep all the Game Center code in one spot.

When the singleton object starts up, it will register for the “authentication changed” notification.

The game will call a method on the singleton object to authenticate the user.

Whenever the user is authentiated (or logs out), the “authentication changed” callback will be called.

The callback will keep track of whether the user is currently authenticated, for use later.

Now that you’re armed with this plan, let’s try it out!

Authenticate the Local User: Implementation

In the Cat Race Xcode project, go to File\New\New File, choose iOS\Cocoa Touch\Objective-C class, and click Next. Enter NSObject for Subclass of, click Next, name the new class GCHelper.m, and click Finish.

Replace GCHelper.h with the following:

This imports the GameKit header file, and then creates an object with two booleans – one to keep track of if game center is available on this device, and one to keep track of whether the user is currently authenticated.

It also creates a property so the game can tell if game center is available, a static method to retrieve the singleton instance of this class, and another method to authenticate the local user (which will be called when the app starts up).

Next switch to GCHelper.m and add the following right inside the @implementation:

This synthesizes the gameCenterAvailable property, then defines the method to create the singleton instance of this class.

Note there are many ways of writing singleton methods, but this is the simplest way when you don’t have to worry about multiple threads trying to initialize the singleton at the same time.

Next add the following method right after the sharedInstance method:

This method is straight from Apple’s Game Kit Programming Guide. It’s the way to check if Game Kit is available on the current device.

By making sure Game Kit is available before using it, this app can still run on iOS 4.0 or earlier (just without network capabilities).

Next add the following right after the isGameCenterAvailable method:

The init method checks to see if Game Center is available, and if so registers for the “authentication changed” notification. It’s important that the app registers for this notification before attempting to authenticate the user, so that it’s called when the authentication completes.

The authenticationChanged callback is very simple at this point – it checks to see whether the change was due to the user being authenticate or un-authenticated, and updates a status flag accordingly.

Note that in practice this might be called several times in a row for authentication or un-authentication, so by making sure the userAuthenticated flag is different than the current status, it only logs if there’s a change since last time.

Finally, add the method to authenticate the local user right after the authenticationChanged method:

This calls the authenticateWithCompletionHandler method mentioned earlier to tell Game Kit to authenticate the user. Note it doesn’t pass in a completion handler. Since you’ve already registered for the “authentication changed” notification it’s not necessary.

OK – GCHelper now contains all of the code necessary to authenticate the user, so you just have to use it! Switch to AppDelegate.m and make the following changes:

This creates the Singleton instance (which registers for the “authentication changed” callback as part of initialization), then calls the authenticateLocalUser method.

Almost done! The last step is to add the Game Kit framework into your project. To do this, select the CatRace project in the upper left of Groups & Files, select the Build Phases tab, expand the “Link Binary with Libraries” section, and click the “+” button.

Select GameKit.framework, and click Add. Change the type from Required to Optional, and your screen should look like the following:

That’s it! Compile and run your project, and if you’re logged into Game Center you should see something like the following:

Now that you’ve authenticated the user, you can start moving onto the fun stuff – such as finding someone to play with!

Matchmaker, Matchmaker, Make Me A Match

There are two ways to find someone to play with via Game Center: search for match programatically, or use the built-in matchmaking user interface.

In this tutorial, we’re going to use the built-in matchmaking user interface. The idea is when you want to find a match, you set up some parameters in a GKMatchRequest object, then create and display an instance of a GKMatchmakerViewController.

Let’s see how this works. First make a few changes to GCHelper.h:

There’s a bunch of new stuff here, so let’s go over it bit by bit.

You define a protocol called GCHelperDelegate that you’ll use to notify another object of when important events happen, such as the match starting, ending, or receiving data from the other party. For this game, your Cocos2D layer will be implementing this protocol.

The GCHelper object is marked as implementing two protocols. The first is so that the matchmaker user interface can notify this object when a match is found or not. The second is so that Game Center can notify this object when data is received or the connection status changes.

Creates some new instance variables and properties to keep track of a view controller that will be used to present the matchmaker user interface, a reference to the match, whether it’s started or not, and the delegate.

Creates a new method that the Cococs2D layer will call to look for someone to play with.

Next switch to GCHelper.m and make the following changes:

This is the method that the Cocos2D layer will call to find a match. It does nothing if Game Center is not available.

It initializes the match as not started yet, and the match object as nil. It stores away the view controller and delegate for later use, and dismisses any previously existing modal view controllers (in case a GKMatchmakerViewController is already showing).

Then it moves into the important stuff. The GKMatchRequest object allows you to configure the type of match you’re looking for, such as a minimum and maximum amount of players. This method sets it to whatever is passed in (which for this game will be min 2, max 2 players).

Next it creates a new instance of the GKMatchmakerViewController with the given request, sets its delegate to the GCHelper object, and uses the passed-in view controller to show it on the screen.

The GKMatchmakerViewController takes over from here, and allows the user to search for a random player and start a game. Once it’s done some callback methods will be called, so let’s add those next:

If the user cancelled finding a match or there was an error, it just closes the matchmaker view.

However if a match was found, it squirrels away the match object and sets the delegate of the match to be the GCHelper object so it can be notified of incoming data and connection status changes.

It also runs a quick check to see if it’s time to actually start the match. The match object keeps track of how many players still need to finish connecting as the “expectedPlayerCount”.

If this is 0, everybody’s ready to go. Right now we’re just going to log that out – later on we’ll actually do something interesting here.

Next, add the implementation of the GKMatchDelegate callbacks:

match:didReceiveData:fromPlayer is called when another player sends data to you. This method simply forwards the data onto the delegate (which will be the Cocos2D layer in this game), so that it can do the game-specific stuff with it.

For match:player:didChangState, when the player connects you need to check if all the players have connected in, so you can start the match once they’re all in. Other than that, if a player disconnects it sets the match as ended and notifies the delegate.
The final two methods are called when there’s an error with the connection. In either case, it marks the match as ended and notifies the delegate.

OK, now that we have this code to establish a match, let’s use it in our HelloWorldLayer. Switch to HelloWorldLayer.h and make the following changes:

Then switch to HelloWorldLayer.m and make the following changes:

The most important part here is in the init method. It gets the RootViewController from the AppDelegate, because that is the view controller that will present the matchmaker view controller. Then it calls the new method you just wrote on GCHelper to find a match by presenting the matchmaker view controller.

The rest is just some stub functions when a match begins or ends that you’ll be implementing later.

One last thing. By default the Cocos2D template does not contain a property for the RootViewController in the App Delegate, so you have to add one. Switch to AppDelegate.h and add the following:

And switch to AppDelegate.m and synthesize it:

That’s it! Compile and run your app, and you should see the matchmaker view controller start up:

Now run your app on a different device so you have two running at the same time (i.e. maybe your simulator and your iPhone).

Important: Make sure you are using a different Game Center account on each device, or it won’t work!

Click “Play Now” on both devices, and after a little bit of time, the matchkaker view controller should go away, and you should see something like this in your console log:

Congrats – you now have made a match between two devices! You’re on your way to making a networked game!

Landscape Orientation and GKMatchmakerViewController

You might have noticed that by default, the GKMatchmakerViewController appears in portrait orientation. Obviously, this is quite annoying since this Cocos2D game is in landscape!

Luckily, you can put in a patch for this with Objective-C categories by forcing the GKMatchmakerViewController to accept landscape-only orientations.

To do this, Go to File\New\New File, choose iOS\Cocoa Touch\Objective-C class, and click Next. Enter NSObject for Subclass of, click Next, name the new class GKMatchmakerViewController-LandscapeOnly.m, and click Finish.

Replace the contents of GKMatchmakerViewController-LandscapeOnly.h with the following:

Then replace the contents of GKMatchmakerViewController-LandscapeOnly.m with the following:

And that’s it! Compile and run your app and the view controller should show up in landscape mode right away:

Where To Go From Here?

Here is a sample project with all of the code we’ve developed so far in this tutorial.

In the second part of the tutorial series, we’ll cover how to send data back and forth between each device in the game, and wrap up the game into an exciting cat vs. kid race!

In the meantime, if you have any questions, comments, or suggestions for future tutorials, please join the forum discussion below! And don’t forget to vote for what tutorial you’d like to see next in the sidebar! :] (Source: Ray Wenderlich)


上一篇:

下一篇: