发送和检索节点的位置

时间:2019-03-13 13:35:53

标签: ios swift firebase firebase-realtime-database

我正在使用Firebase实时数据库发送移动节点的x和y位置,以便每个玩家可以看到其他玩家节点的移动。但是它非常滞后,我不确定是什么问题。

在更新功能中,如果当前玩家=游戏中玩家的玩家[0],则它控制一个节点(圆圈1),如果当前玩家=玩家[1],则它控制另一个节点(圆圈2)。节点位置的x和y坐标被发送到数据库,并由其他玩家在didMove中检索,并更新节点在其视图中的位置。

override func update(_ currentTime: TimeInterval) {
    let circle1PositionX = circle1.position.x
    let circle1PositionY = circle1.position.y
    let circle2PositionX = circle2.position.x
    let circle2PositionY = circle2.position.y
    let dict1 = ["x": circle1PositionX, "y": circle1PositionY] as [String: Any]
    let dict2 = ["x": circle2PositionX, "y": circle2PositionY] as [String: Any]   

    if (currentPlayer as? String == playersArray[1] as? String) {
         GameDataSource.ref.child("locations").child(gameID as! String)
         .child(playersArray[1] as! String).child("circle").setValue(dict2)   
    }
    else if (currentPlayer as? String == playersArray[0] as? String) {    
         GameDataSource.ref.child("locations").child(gameID as! String)
         .child(playersArray[0] as! String).child("circle").setValue(dict1)   
    }

然后在didMove中调用此函数(只是一个片段)。

func observePlayerPosition() {
    guard let players = self.userData?.mutableArrayValue(forKey: "players"), let currentPlayer =  self.userData?.value(forKey: "currentPlayer"), let gameID = self.userData?.value(forKey: "gameID") else {
        print("Something is missing")
        return
    }
    let playersArray = players as Array

    if (currentPlayer as? String == playersArray[0] as? String) {

        GameDataSource.ref.child("locations").child(gameID as! String).child(playersArray[1] as! String).observe(.childChanged) { (snapshot) in
            GameDataSource.ref.child("locations").child(gameID as! String).child(playersArray[1] as! String).child("circle").observeSingleEvent(of: .value, with: { (snapshot) in
                guard let okx = snapshot.childSnapshot(forPath: "x").value as? Double else {
                    return
                }
                guard let oky = snapshot.childSnapshot(forPath: "y").value as? Double else {
                    return
                }

                self.circle2.position = CGPoint(x: okx, y: oky)  
            }) 
        }

0 个答案:

没有答案