【问题标题】:Transferring Interger once a game has started GameKit游戏开始后转移 Interger GameKit
【发布时间】:2020-07-15 03:14:04
【问题描述】:

我已成功使用 Apple 文档通过 Game Center 连接两个玩家并开始游戏。然而,几天来我一直在努力让应用程序在两个玩家之间发送数据。

我只需要在两个玩家之间发送一个整数,但甚至无法运行文档代码,即使在创建结构等之后也是如此。我看过的示例已经过时或者我无法构建它们.

func sendPosition() {

let messageToSend = 123

//what do I need to do messageToSend to send it?

    do {
        try match.sendData(toAllPlayers: packet, with: .unreliable)
    } catch {
    }

    if error != nil {

        // Handle the error.
    }

}

    func match(_ match: GKMatch, didReceive data: Data, fromRemotePlayer player: GKPlayer) {
       //What do I need to do to receive the data?

       }

如果有人能提供一些我可以在 Swift 5+ 中试验的工作代码,我将不胜感激。

【问题讨论】:

    标签: game-center multiplayer gamekit swift5.2


    【解决方案1】:

    经过一些阅读和播放我的原始代码似乎工作!如果它对其他人有帮助:

    发送:

    @IBAction func sendDataBtn(_ sender: Any) {
        print("sending data")
        let dataString = "Hello, World!"
        let dataToSend = dataString.data(using: .utf8)
        do {
        try myMatch.sendData(toAllPlayers: dataToSend!, with: .reliable)
        } catch {
            print(error.localizedDescription)
        }
    }
    

    接收:

    func match(_ match: GKMatch, didReceive data: Data, fromRemotePlayer player: GKPlayer) {
        print("Data Received")
        let receivedData = String(data: data, encoding: .utf8)
        messageLbl.text = receivedData
    }
    

    【讨论】:

      【解决方案2】:

      我创建了一个“容器”来发送数据,这样我可以一次性添加指令以及需要完成的操作。例如;

          var type:String = "jump"
          var data:CGPoint = CGPoint(x:10,y:10)
          
          let container:[Any] = [type, data]
      
          
      do {
            let dataToSend = try NSKeyedArchiver.archivedData(withRootObject: container, requiringSecureCoding: true)
              try match.sendData(toAllPlayers: packet, with: .unreliable)
          } catch {
          }
      
          if error != nil {
      
              // Handle the error.
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-14
        • 1970-01-01
        • 2015-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多