Unity3d使用蓝牙(bluetooth)开发IOS点对点网络游戏
著作权声明:本文由http://www.cnblogs.com/icker 原创,欢迎转载分享。转载时请保留该声明和作者博客链接,谢谢!
最近使用Unity3d制作的IOS游戏需要加入联网对战功能功能,因此使用ObjC语言利用IOS SDK的GameKit.framework的Peer-to-peer Connectivity实现了网络连接,在此分享。
啥话都不说,先上代码。点我下载工程文件,
类NetWorkP2P,继承自NSObject。提供GKSessionDelegate和GKPeerPickerControllerDelegate的实现。并且利用单例模式实现一个类方法+( NetWorkP2P *) sharedNetWorkP2P;此方法返回一个NetWorkP2P的实例。

%E5%BC%80%E5%8F%91IOS%E7%82%B9%E5%AF%B9%E7%82%B9%E7%BD%91%E7%BB%9C%E6%B8%B8%E6%88%8F%20-%20%E9%A3%8E%E4%BA%91%E6%B0%B8%E6%9D%B0%20-%20%E5%8D%9A%E5%AE%A2%E5%9B%AD_files/copycode.gif)
//
// NetWorkP2P.h
// P2PTapWar
//
// Created by on 11-9-14.
// Copyright 2011年 __MyCompanyName__. All rights reserved.
// #import<Foundation/Foundation.h>
#import<GameKit/GameKit.h> #define AMIPHD_P2P_SESSION_ID @"amiphd-p2p"
#define START_GAME_KEY @"startgame"
#define TIME_KEY @"time"
#define END_GAME_KEY @"endgame"
#define TAP_COUNT_KEY @"taps"
#define TIMES_KEY @"times" @interface NetWorkP2P : NSObject<GKSessionDelegate,GKPeerPickerControllerDelegate>{ UInt32 playerScore;
UInt32 opponentScore; UInt32 playerTimes;
UInt32 opponentTimes; NSString *opponentID;
BOOL actingAsHost;
GKSession *gkSession;
}
+( NetWorkP2P *) sharedNetWorkP2P;
-(void)showPeerPickerController; -(void)addTheScore: (UInt32)score;
-(void)addTimes; -(UInt32)getOpponentScore;
-(UInt32)getPlayerScore;
-(UInt32)getPlayerTimes;
-(UInt32)getOpponentTimes; -(NSString *)getOpponentID;
@end
%E5%BC%80%E5%8F%91IOS%E7%82%B9%E5%AF%B9%E7%82%B9%E7%BD%91%E7%BB%9C%E6%B8%B8%E6%88%8F%20-%20%E9%A3%8E%E4%BA%91%E6%B0%B8%E6%9D%B0%20-%20%E5%8D%9A%E5%AE%A2%E5%9B%AD_files/copycode.gif)

类NetWorkP2P的实现文件,fileName:NetWorkP2P.m

%E5%BC%80%E5%8F%91IOS%E7%82%B9%E5%AF%B9%E7%82%B9%E7%BD%91%E7%BB%9C%E6%B8%B8%E6%88%8F%20-%20%E9%A3%8E%E4%BA%91%E6%B0%B8%E6%9D%B0%20-%20%E5%8D%9A%E5%AE%A2%E5%9B%AD_files/copycode.gif)
//
// NetWorkP2P.m
// P2PTapWar
//
// Created by on 11-9-14.
// Copyright 2011年 __MyCompanyName__. All rights reserved.
// #import"NetWorkP2P.h" @implementation NetWorkP2P
+(NetWorkP2P *) sharedNetWorkP2P{
static NetWorkP2P *sharedNetWorkObject;
if(!sharedNetWorkObject)
sharedNetWorkObject=[[NetWorkP2P alloc] init];
return sharedNetWorkObject;
} - (id)init
{
self = [super init];
if (self) {
// Initialization code here.
} return self;
}
-(UInt32)getPlayerScore{
return playerScore;
}
-(UInt32)getOpponentScore{
return opponentScore;
}
-(UInt32)getOpponentTimes{
return opponentTimes;
}
-(UInt32)getPlayerTimes{
return playerTimes;
}
-(NSString *)getOpponentID
{
return opponentID;
}
-(void) showPeerPickerController
{
if(!opponentID)
{
actingAsHost=YES;
GKPeerPickerController *peerPickerContrller=[[GKPeerPickerController alloc] init];
peerPickerContrller.delegate=self;
peerPickerContrller.connectionTypesMask=GKPeerPickerConnectionTypeNearby;
[peerPickerContrller show];
}
}
-(void)addTheScore:(UInt32)score
{
playerScore+=score;
NSMutableData *message=[[NSMutableData alloc]init];
NSKeyedArchiver *archiver=[[NSKeyedArchiver alloc]initForWritingWithMutableData:message];
[archiver encodeInt:playerScore forKey:TAP_COUNT_KEY];
[archiver finishEncoding];
GKSendDataMode sendMode=GKSendDataUnreliable;
[gkSession sendDataToAllPeers:message withDataMode:sendMode error:NULL];
[archiver release];
[message release]; }
-(void)addTimes
{
playerTimes++;
NSMutableData *message=[[NSMutableData alloc]init];
NSKeyedArchiver *archiver=[[NSKeyedArchiver alloc] initForWritingWithMutableData:message];
[archiver encodeInt:playerTimes forKey:TIMES_KEY];
[archiver finishEncoding];
GKSendDataMode sendMode=GKSendDataUnreliable;
[gkSession sendDataToAllPeers:message withDataMode:sendMode error:NULL];
[archiver release];
[message release];
}
#pragma mark game logic -(void) initGame{
playerScore=0;
opponentScore=0;
}
-(void) hostGame{
[self initGame];
NSMutableData *message=[[NSMutableData alloc] init];
NSKeyedArchiver *archiver=[[NSKeyedArchiver alloc] initForWritingWithMutableData:message];
[archiver encodeBool:YES forKey:START_GAME_KEY];
[archiver finishEncoding]; NSError *sendErr=nil;
[gkSession sendDataToAllPeers:message withDataMode:GKSendDataReliable error:&sendErr];
if (sendErr) {
NSLog(@"send greeting failed : %@",sendErr);
}
[message release];
[archiver release];
}
-(void) joinGame{
[self initGame];
}
-(void) showEndGameAlert{
}
-(void) endGame{
opponentID=nil;
[gkSession disconnectFromAllPeers];
[self showEndGameAlert];
} #pragma mark GKPeerPickerControllerDelegate methods -(GKSession *) peerPickerController:(GKPeerPickerController *)picker sessionForConnectionType:(GKPeerPickerConnectionType)type
{
if(!gkSession)
{
gkSession=[[GKSession alloc] initWithSessionID:AMIPHD_P2P_SESSION_ID displayName:nil sessionMode:GKSessionModePeer];
gkSession.delegate=self;
}
return gkSession;
}
-(void) peerPickerController:(GKPeerPickerController *) picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session
{
NSLog ( @"connected to peer %@", peerID);
[session retain]; // TODO: who releases this?
[picker dismiss];
[picker release];
}
- (void)peerPickerControllerDidCancel:(GKPeerPickerController *)picker {
NSLog ( @"peer picker cancelled");
[picker release];
} #pragma mark GKSessionDelegate methods //START:code.P2PTapWarViewController.peerdidchangestate
- (void)session:(GKSession *)session peer:(NSString *)peerID
didChangeState:(GKPeerConnectionState)state {
switch (state)
{
case GKPeerStateConnected:
[session setDataReceiveHandler: self withContext: nil];
opponentID = peerID;
actingAsHost ? [self hostGame] : [self joinGame];
break;
}
}
//END:code.P2PTapWarViewController.peerdidchangestate //START:code.P2PTapWarViewController.didreceiveconnectionrequestfrompeer
- (void)session:(GKSession *)session
didReceiveConnectionRequestFromPeer:(NSString *)peerID {
actingAsHost = NO;
}
//END:code.P2PTapWarViewController.didreceiveconnectionrequestfrompeer - (void)session:(GKSession *)session connectionWithPeerFailed:(NSString *)peerID withError:(NSError *)error {
NSLog (@"session:connectionWithPeerFailed:withError:");
} - (void)session:(GKSession *)session didFailWithError:(NSError *)error {
NSLog (@"session:didFailWithError:");
}
#pragma mark receive data from session
-(void) receiveData: (NSData *) data fromPeer : (NSString *) peerID inSession: (GKSession *) session context:(void*) context{
NSKeyedUnarchiver *unarchiver=[[NSKeyedUnarchiver alloc] initForReadingWithData:data];
if([unarchiver containsValueForKey:TAP_COUNT_KEY])
{
opponentScore=[unarchiver decodeIntForKey:TAP_COUNT_KEY];
}
if([unarchiver containsValueForKey:TIMES_KEY])
{
opponentTimes=[unarchiver decodeIntForKey:TIMES_KEY];
}
if([unarchiver containsValueForKey:END_GAME_KEY])
{
[self endGame];
}
if([unarchiver containsValueForKey:START_GAME_KEY])
{
[self joinGame];
}
[unarchiver release];
}
@end
%E5%BC%80%E5%8F%91IOS%E7%82%B9%E5%AF%B9%E7%82%B9%E7%BD%91%E7%BB%9C%E6%B8%B8%E6%88%8F%20-%20%E9%A3%8E%E4%BA%91%E6%B0%B8%E6%9D%B0%20-%20%E5%8D%9A%E5%AE%A2%E5%9B%AD_files/copycode.gif)

fileName:NetWorkP2PBinding.m在此文件中实现C语言接口,以方便在UnityScript中调用。

%E5%BC%80%E5%8F%91IOS%E7%82%B9%E5%AF%B9%E7%82%B9%E7%BD%91%E7%BB%9C%E6%B8%B8%E6%88%8F%20-%20%E9%A3%8E%E4%BA%91%E6%B0%B8%E6%9D%B0%20-%20%E5%8D%9A%E5%AE%A2%E5%9B%AD_files/copycode.gif)
//NetWorkP2PBinding.mm
#import"NetWorkP2P.h"
extern"C"{
void _showPeerPicker()
{
[[NetWorkP2P sharedNetWorkP2P] showPeerPickerController];
NSLog(@"call the mothed _showPeerPicker");
}
constchar* _getName()
{
return [@"fyn" UTF8String];
}
int _getOpponentScore()
{
return [[NetWorkP2P sharedNetWorkP2P]getOpponentScore];
}
int _getPlayerScore()
{
return [[NetWorkP2P sharedNetWorkP2P]getPlayerScore];
}
void _addTheScore( UInt32 score)
{
[[NetWorkP2P sharedNetWorkP2P] addTheScore:score];
}
void _addTheTimes()
{
[[NetWorkP2P sharedNetWorkP2P] addTimes];
}
int _getOpponentTimes()
{
return [[NetWorkP2P sharedNetWorkP2P] getOpponentTimes];
}
int _getPlayerTimes()
{
return [[NetWorkP2P sharedNetWorkP2P] getPlayerTimes];
}
constchar* _getOpponentID()
{
return [[[NetWorkP2P sharedNetWorkP2P ]getOpponentID] UTF8String];
}
}
%E5%BC%80%E5%8F%91IOS%E7%82%B9%E5%AF%B9%E7%82%B9%E7%BD%91%E7%BB%9C%E6%B8%B8%E6%88%8F%20-%20%E9%A3%8E%E4%BA%91%E6%B0%B8%E6%9D%B0%20-%20%E5%8D%9A%E5%AE%A2%E5%9B%AD_files/copycode.gif)

FileName:P2PBinding.cs 这是在Unity3d中C#脚本,在这里面调用NetWorkP2PBinding.mm实现的C语言方法。

%E5%BC%80%E5%8F%91IOS%E7%82%B9%E5%AF%B9%E7%82%B9%E7%BD%91%E7%BB%9C%E6%B8%B8%E6%88%8F%20-%20%E9%A3%8E%E4%BA%91%E6%B0%B8%E6%9D%B0%20-%20%E5%8D%9A%E5%AE%A2%E5%9B%AD_files/copycode.gif)
//P2PBinding.cs using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices; publicclass P2PBinding{
[DllImport("__Internal")]
privatestaticexternvoid _showPeerPicker(); publicstaticvoid showPeerPicker()
{
if(Application.platform==RuntimePlatform.IPhonePlayer)
_showPeerPicker();
} [DllImport("__Internal")]
privatestaticexternint _getOpponentScore(); [DllImport("__Internal")]
privatestaticexternint _getOpponentTimes(); [DllImport("__Internal")]
privatestaticexternint _getPlayerScore(); [DllImport("__Internal")]
privatestaticexternint _getPlayerTimes(); [DllImport("__Internal")]
privatestaticexternvoid _addTheTimes(); [DllImport("__Internal")]
privatestaticexternvoid _addTheScore(int score); publicstaticint getOpponentScore()
{
if(Application.platform==RuntimePlatform.IPhonePlayer)
{
return _getOpponentScore();
}
return-1;
}
publicstaticint getOpponentTimes()
{
if(Application.platform==RuntimePlatform.IPhonePlayer)
{
return _getOpponentTimes();
}
return-1;
}
publicstaticint getPlayerScore()
{
if(Application.platform==RuntimePlatform.IPhonePlayer)
{
return _getPlayerScore();
}
return-1;
}
publicstaticint getPlayerTimes()
{
if(Application.platform==RuntimePlatform.IPhonePlayer)
{
return _getPlayerTimes();
}
return-1;
}
publicstaticvoid addTheScore(int score)
{
if(Application.platform==RuntimePlatform.IPhonePlayer)
{
_addTheScore(score);
}
}
publicstaticvoid addTheTimes()
{
_addTheTimes();
}
}
%E5%BC%80%E5%8F%91IOS%E7%82%B9%E5%AF%B9%E7%82%B9%E7%BD%91%E7%BB%9C%E6%B8%B8%E6%88%8F%20-%20%E9%A3%8E%E4%BA%91%E6%B0%B8%E6%9D%B0%20-%20%E5%8D%9A%E5%AE%A2%E5%9B%AD_files/copycode.gif)

FileName:GameDate.cs 此文件提供游戏的数据,并保持和NetWorkP2P文件中数据同步,将此文件附加到一个GameObject上。

%E5%BC%80%E5%8F%91IOS%E7%82%B9%E5%AF%B9%E7%82%B9%E7%BD%91%E7%BB%9C%E6%B8%B8%E6%88%8F%20-%20%E9%A3%8E%E4%BA%91%E6%B0%B8%E6%9D%B0%20-%20%E5%8D%9A%E5%AE%A2%E5%9B%AD_files/copycode.gif)
using UnityEngine;
using System.Collections; publicclass GameDate : MonoBehaviour { publicstring opponentID; publicint playerTimes;
publicint opponentTimes;
publicint playerScore;
publicint opponentScore; // Use this for initialization
void Start () {
P2PBinding.showPeerPicker();
} // Update is called once per frame
void Update () {
opponentTimes=P2PBinding.getOpponentTimes();
opponentScore=P2PBinding.getOpponentScore();
}
}
%E5%BC%80%E5%8F%91IOS%E7%82%B9%E5%AF%B9%E7%82%B9%E7%BD%91%E7%BB%9C%E6%B8%B8%E6%88%8F%20-%20%E9%A3%8E%E4%BA%91%E6%B0%B8%E6%9D%B0%20-%20%E5%8D%9A%E5%AE%A2%E5%9B%AD_files/copycode.gif)

%E5%BC%80%E5%8F%91IOS%E7%82%B9%E5%AF%B9%E7%82%B9%E7%BD%91%E7%BB%9C%E6%B8%B8%E6%88%8F%20-%20%E9%A3%8E%E4%BA%91%E6%B0%B8%E6%9D%B0%20-%20%E5%8D%9A%E5%AE%A2%E5%9B%AD_files/1.png)
Unity3d使用蓝牙(bluetooth)开发IOS点对点网络游戏的更多相关文章
- iOS蓝牙BLE开发
蓝牙是一个标准的无线通讯协议,具有设备成本低.传输距离近和功耗低等特点,被广泛的应用在多种场合.蓝牙一般分为传统蓝牙和BLE两种模式:传统蓝牙可以传输音频等较大数据量,距离近.功耗相对大:而BLE则用 ...
- iOS 上的蓝牙框架 - Core Bluetooth for iOS
原文: Core Bluetooth for iOS 6 Core Bluetooth 是在iOS5首次引入的,它允许iOS设备可以使用健康,运动,安全,自动化,娱乐,附近等外设数据.在iOS 6 中 ...
- Unity3d开发IOS游戏 基础
Unity3d开发IOS游戏 基础 @阿龙 - 649998群 1.先说明两个问题,我在WIN7下面的U3D里面,用了雅黑字体,但是导出为ios后,字体就看不见了,这是为什么呢?这是需要在MAC下找 ...
- Android开发之蓝牙(Bluetooth)操作(一)--扫描已经配对的蓝牙设备
版权声明:本文为博主原创文章,未经博主允许不得转载. 一. 什么是蓝牙(Bluetooth)? 1.1 BuleTooth是目前使用最广泛的无线通信协议 1.2 主要针对短距离设备通讯(10m) ...
- 蓝牙(Bluetooth) IEEE 802.15.1 协议学习
catalogue . 蓝牙概念 . 配对和连接 . 机密安全性 . 蓝牙协议分类 . 蓝牙协议栈 1. 蓝牙概念 蓝牙(Bluetooth)是一种无线技术标准,可实现固定设备.移动设备和楼宇个人域网 ...
- (转)火溶CEO王伟峰:Unity3D手机网游开发
今天看到这篇文章,感觉很不错,尤其是那句“Unity3D的坑我觉得最严重的坑就是没有懂3D的程序员,把Unity当成Office用”. 转自http://blog.csdn.net/wwwang891 ...
- 深入了解Android蓝牙Bluetooth——《基础篇》
什么是蓝牙? 也可以说是蓝牙技术.所谓蓝牙(Bluetooth)技术,实际上是一种短距离无线电技术,是由爱立信公司公司发明的.利用"蓝牙"技术,能够有效地简化掌上电脑.笔记本电 ...
- iOS开发-iOS 10 由于权限问题导致崩溃的那些坑
iOS开发-iOS 10 由于权限问题导致崩溃的那些坑 6月份的WWDC大会结束有一段时间了,相信很多开发者也是在努力工作的闲时用着Xcode8 Beta版学习着新的特性吧. 使用Xcode8写自己 ...
- BLK-MD-BC04-B蓝牙模块开发说明
BLK-MD-BC04-B蓝牙模块开发说明 日期:2011-9-24 浏览次数:4178 BLK-MD-BC04-B蓝牙通信模块, BLK-MD-BC04-B蓝牙通信模块 为本公司自主开发的智 ...
随机推荐
- grootJs 系统常用API接受
groot.absUrl(url) 把相对路径转换为绝对路径 groot.model 把vm对象转换为json 去掉系统生成的的属性groot.model groot.log 输出到控制台 兼容低版本 ...
- 中国IT 未来何在
许久之前,已对国内IT业的一些问题颇有看法,而今又恰逢360与AV-C的纠缠,实在忍不住要发发牢骚.IT在中国,发展不过二十来年,却以迅雷之速横扫各个领域,令人感叹,此成就是不可否认的:然而,发展 ...
- C# ArcEngine创建内存图层(转载)
C#+Arcengine---创建内存图层 分类:技术文档 2009-12-11 14:43阅读(1498)评论(0) #region 在内存中创建图层 /// <summary& ...
- 英语etc怎么发音、单词来历
etc是等等的意思,与and so on 相同 音标/et'set(a)ra/ 源于法语et cetera,也是等等的意思 在计算机操作系统目录(linux和windows)有一个叫etc的目录 里面 ...
- Spring配置文件详解:<context:annotation-config/>和<context:component-scan base-package=""/>和<mvc:annotation-driven />
<context:annotation-config/> 在基于主机方式配置Spring时,Spring配置文件applicationContext.xml,你可能会见<contex ...
- 如何在Oracle中导入dmp文件
Oracle数据导入导出imp/exp就相当于oracle数据还原与备份.exp命令可以把数据从远程数据库服务器导出到本地的dmp文件,imp命令可以把dmp文件从本地导入到远处的数据库服务器中. 利 ...
- win8.1右键新建菜单添加新建php文件
最近在学习php没使用IDE,一直使用编辑器,但每次新建文件都要手动该扩展名比较麻烦.于是想着能不能在右键新建菜单直接新建php文件.于是开始百度... 步骤一:win+R打开运行(管理员身份运行) ...
- Java编程思想学习(六) 多态
1.Java语言的三大特性:继承.封装和多态. 继承:复用类的一种方法,可以简省很多代码: 封装:通过合并特征和行为来创建新的数据类型.[这种“数据类型”跟Java本身提供的8大“基本数据类型”的地位 ...
- vim YouCompleteMe
http://www.ithao123.cn/content-1906969.html http://www.it165.net/os/html/201503/12190.html
- Android自动化测试框架对比
1.Monkeyrunner:优点:操作最为简单,可以录制测试脚本,可视化操作:缺点:主要生成坐标的自动化操作,移植性不强,功能最为局限:2.Rubotium:主要针对某一个APK进行自动化测试,AP ...