我正在使用Swift中的MultipeerConnectivityFramework开发多人游戏。我的问题是,这不是很顺利,延迟相对较长。
我的意思是,连接电话上的更改并不会立即发生,但延迟会导致游戏卡住。
所以开始简单:每当玩家触摸屏幕时,节点应该在两个屏幕上移动。所以当然每次用户触摸屏幕时我都需要发送一条消息。所以在我的touchesBegan
方法中,我称之为send-method:
func sendMessage(dict:NSDictionary){
let messageDict = dict
let messageData = NSJSONSerialization.dataWithJSONObject(messageDict, options: NSJSONWritingOptions.PrettyPrinted, error: nil)
appDelegate.mpcHandler.session.sendData(messageData, toPeers: appDelegate.mpcHandler.session.connectedPeers, withMode: MCSessionSendDataMode.Reliable, error: nil)
}
就像那样:
sendMessage(["moved":MoveDirection.Left.rawValue])
然后,我在另一台设备上接收它并运行该功能来更新节点位置:
func handleReceivedDataWithNotification(notification:NSNotification){
let userInfo = notification.userInfo! as Dictionary
let receivedData:NSData = userInfo["data"] as NSData
let message = NSJSONSerialization.JSONObjectWithData(receivedData, options: NSJSONReadingOptions.AllowFragments, error: nil) as NSDictionary
if let mess: AnyObject = message.objectForKey("lostState"){
gameOver = true
createGameOverLabel(mess as String)
}else if let mess: AnyObject = message.objectForKey("higher"){
println(mess)
let coNumber = mess as Int
println(yourNumber)
if(coNumber > yourNumber){
leftAndRight = true
}else{
leftAndRight = false
}
}else if let mess:AnyObject = message.objectForKey("moved"){
var moved = mess as Int
var move = moveHeight/3
switch moved{
case MoveDirection.Left.rawValue:
moveNode.position.x -= move
case MoveDirection.Right.rawValue:
moveNode.position.x += move
case MoveDirection.Down.rawValue:
moveNode.position.y -= move
case MoveDirection.Up.rawValue:
moveNode.position.y += move
default:
break
}
}
}
所以我的问题是:我做错了吗?我已经在真正的iPhone 6和真正的iPhone 5上进行了测试。除了GameCenter或其他方式,还有其他选择,以便发送/接收工作更快吗?
答案 0 :(得分:0)
我怀疑你的问题是你试图从后台线程而不是主线程更新UI。在UI反映收到的数据之前,结果显然是很长的延迟。
当收到数据时,在后台线程上调用didReceiveData:fromPeer,如果你发布该方法的通知,则不会在UI线程上。
尝试使用dispatch_async
dispatch_async(dispatch_get_main_queue(), {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleReceivedDataWithNotification:", name: "MPC_DidReceiveDataNotification", object: nil)
})