12 第1页 | 共2 页下一页
返回列表 发新帖
查看: 4926|回复: 12
打印 上一主题 下一主题

Unity3d使用蓝牙开发IOS点对点网络游戏(转)

[复制链接]

1023

主题

3

听众

359

积分

设计实习生

Rank: 2

纳金币
335582
精华
0

最佳新人

跳转到指定楼层
楼主
发表于 2011-9-29 08:39:03 |只看该作者 |倒序浏览
类NetWorkP2P,继承自NSObject。提供GKSessionDelegate和GKPeerPickerControllerDelegate的实现。并且利用单例模式实现一个类方法+( NetWorkP2P *) sharedNetWorkP2P;此方法返回一个NetWorkP2P的实例。
//
//  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
类NetWorkP2P的实现文件,fileName:NetWorkP2P.m
//
//  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)addTheScoreUInt32)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 *) peerPickerControllerGKPeerPickerController *)picker sessionForConnectionTypeGKPeerPickerConnectionType)type
{
    if(!gkSession)
    {
        gkSession=[[GKSession alloc] initWithSessionID:AMIPHD_P2P_SESSION_ID displayName:nil sessionMode:GKSessionModePeer];
        gkSession.delegate=self;
    }
    return gkSession;
}
-(void) peerPickerControllerGKPeerPickerController *) picker didConnectPeerNSString *)peerID toSessionGKSession *)session
{
    NSLog ( @"connected to peer %@", peerID);
    [session retain];      // TODO: who releases this?
    [picker dismiss];
    [picker release];
}
- (void)peerPickerControllerDidCancelGKPeerPickerController *)picker {
    NSLog ( @"peer picker cancelled");
    [picker release];
}

#pragma mark GKSessionDelegate methods

//START:code.P2PTapWarViewController.peerdidchangestate
- (void)sessionGKSession *)session peerNSString *)peerID
didChangeStateGKPeerConnectionState)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
fileName:NetWorkP2PBinding.m在此文件中实现C语言接口,以方便在UnityScript中调用。
//NetWorkP2PBinding.mm
#import "NetWorkP2P.h"

extern "C"{
    void _showPeerPicker()
    {
        [[NetWorkP2P sharedNetWorkP2P] showPeerPickerController];
        NSLog(@"call the mothed _showPeerPicker");
    }
   
    const char* _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];
    }
    const char * _getOpponentID()
    {
        return [[[NetWorkP2P sharedNetWorkP2P ]getOpponentID] UTF8String];
    }
}
FileName2PBinding.cs 这是在unity3d中C#脚本,在这里面调用NetWorkP2PBinding.mm实现的C语言方法。
//P2PBinding.cs

using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;


public class P2PBinding{
    [DllImport("__Internal")]
    private static extern void _showPeerPicker();
   
    public static void showPeerPicker()
    {
        if(Application.platform==RuntimePlatform.IPhonePlayer)
            _showPeerPicker();
    }
   
    [DllImport("__Internal")]
    private static extern int _getOpponentScore();
   
    [DllImport("__Internal")]
    private static extern int _getOpponentTimes();
   
    [DllImport("__Internal")]
    private static extern int _getPlayerScore();
   
    [DllImport("__Internal")]
    private static extern int _getPlayerTimes();
   
    [DllImport("__Internal")]
    private static extern void _addTheTimes();
   
    [DllImport("__Internal")]
    private static extern void _addTheScore(int score);
   
    public static int getOpponentScore()
    {
        if(Application.platform==RuntimePlatform.IPhonePlayer)
        {
            return _getOpponentScore();
        }
        return -1;
    }
    public static int getOpponentTimes()
    {
        if(Application.platform==RuntimePlatform.IPhonePlayer)
        {
            return _getOpponentTimes();
        }
        return -1;
    }
    public static int getPlayerScore()
    {
        if(Application.platform==RuntimePlatform.IPhonePlayer)
        {
            return _getPlayerScore();
        }
        return -1;
    }
    public static int getPlayerTimes()
    {
        if(Application.platform==RuntimePlatform.IPhonePlayer)
        {
            return _getPlayerTimes();
        }
        return -1;
    }
    public static void addTheScore(int score)
    {
        if(Application.platform==RuntimePlatform.IPhonePlayer)
        {
            _addTheScore(score);
        }
    }
    public static void addTheTimes()
    {
        _addTheTimes();
    }
}
FileName:GameDate.cs 此文件提供游戏的数据,并保持和NetWorkP2P文件中数据同步,将此文件附加到一个GameObject上。
using UnityEngine;
using System.Collections;

public class GameDate : MonoBehaviour {
   
    public string opponentID;
   
    public int playerTimes;
    public int opponentTimes;
    public int playerScore;
    public int opponentScore;
   
    // Use this for initialization
    void Start () {
        P2PBinding.showPeerPicker();
    }
   
    // Update is called once per frame
    void Update () {
        opponentTimes=P2PBinding.getOpponentTimes();
        opponentScore=P2PBinding.getOpponentScore();
    }
}
分享到: QQ好友和群QQ好友和群 腾讯微博腾讯微博 腾讯朋友腾讯朋友 微信微信
转播转播0 分享淘帖0 收藏收藏0 支持支持0 反对反对0
回复

使用道具 举报

Asen    

867

主题

0

听众

1万

积分

外协人员

Rank: 7Rank: 7Rank: 7

纳金币
17488
精华
1
沙发
发表于 2011-9-29 09:22:39 |只看该作者
回复

使用道具 举报

797

主题

1

听众

1万

积分

资深设计师

Rank: 7Rank: 7Rank: 7

纳金币
5568
精华
0

最佳新人 活跃会员 热心会员 灌水之王 突出贡献

板凳
发表于 2011-10-7 11:35:15 |只看该作者
这么多代码都干嘛的
回复

使用道具 举报

   

671

主题

1

听众

3247

积分

中级设计师

Rank: 5Rank: 5

纳金币
324742
精华
0

最佳新人 活跃会员 热心会员 灌水之王 突出贡献

地板
发表于 2012-3-16 23:27:39 |只看该作者
凡系斑竹滴话要听;凡系朋友滴帖要顶!
回复

使用道具 举报

tc    

5089

主题

1

听众

33万

积分

首席设计师

Rank: 8Rank: 8

纳金币
-1
精华
0

最佳新人 活跃会员 热心会员 灌水之王 突出贡献

5#
发表于 2012-3-21 23:20:41 |只看该作者
我也来支持下
回复

使用道具 举报

5969

主题

1

听众

39万

积分

首席设计师

Rank: 8Rank: 8

纳金币
-1
精华
0

最佳新人 活跃会员 热心会员 灌水之王 突出贡献

6#
发表于 2012-3-30 23:20:48 |只看该作者
发了那么多,我都不知道该用哪个给你回帖了,呵呵
回复

使用道具 举报

tc    

5089

主题

1

听众

33万

积分

首席设计师

Rank: 8Rank: 8

纳金币
-1
精华
0

最佳新人 活跃会员 热心会员 灌水之王 突出贡献

7#
发表于 2012-4-16 23:20:40 |只看该作者
佩服,好多阿 ,哈哈
回复

使用道具 举报

tc    

5089

主题

1

听众

33万

积分

首席设计师

Rank: 8Rank: 8

纳金币
-1
精华
0

最佳新人 活跃会员 热心会员 灌水之王 突出贡献

8#
发表于 2012-4-17 23:32:10 |只看该作者
不错 非常经典  实用
回复

使用道具 举报

tc    

5089

主题

1

听众

33万

积分

首席设计师

Rank: 8Rank: 8

纳金币
-1
精华
0

最佳新人 活跃会员 热心会员 灌水之王 突出贡献

9#
发表于 2012-5-9 23:20:57 |只看该作者
呵呵,很漂亮啊
回复

使用道具 举报

462

主题

1

听众

31万

积分

首席设计师

Rank: 8Rank: 8

纳金币
2
精华
0

最佳新人 活跃会员 热心会员 灌水之王 突出贡献

10#
发表于 2012-10-9 23:25:03 |只看该作者
佩服,好多阿 ,哈哈
回复

使用道具 举报

12 第1页 | 共2 页下一页
返回列表 发新帖
您需要登录后才可以回帖 登录 | 立即注册

手机版|纳金网 ( 闽ICP备2021016425号-2/3

GMT+8, 2025-7-26 09:49 , Processed in 0.070691 second(s), 29 queries .

Powered by Discuz!-创意设计 X2.5

© 2008-2019 Narkii Inc.

回顶部