使用 SpriteKit 一次移动多个节点

Moving multiple nodes at once from touch with SpriteKit

我有一个游戏有 3 个 SKSpriteNodes,用户可以使用 touchesBegantouchesMoved 移动它们。然而,当用户移动 nodeA 并经过另一个名为 nodeB 的节点时,nodeB 跟随 nodeA 等等。

我创建了一个 SKSpriteNodes 的数组并使用了一个 for-loop 来让生活更轻松。

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {


        let nodes = [nodeA, nodeB, nodeC]

        for touch in touches {

            let location = touch.location(in: self)

            for node in nodes {

                if node!.contains(location) {

                    node!.position = location
                }

            }


        }

    }

一切正常,除了 nodeA 移动并与 nodeB 交叉路径时,nodeB 跟随 nodeA

我怎样才能做到当用户移动 nodeA 并且 nodeA 通过 nodeBnodeB 不会跟随 nodeA

经过一些试验,我找到了解决这个问题的方法。

我发现通过名称选择节点 属性 可以解决问题,而不是通过触摸的位置选择节点。

显示的代码是在 touchesMoved 和 touchesBegan 方法中实现的

//name of the nodes
    let nodeNames = ["playO", "playOO", "playOOO", "playX", "playXX", "playXXX"]
//the actual nodes
    let player = [playerO, playerOO, playerOOO, playerX, playerXX, playerXXX]

        for touch in touches {

            let pointOfTouch = touch.location(in: self)
            let tappedNode = atPoint(pointOfTouch)
            let nameOfTappedNode = tappedNode.name

            for i in 0..<nodeNames.count {

                if nameOfTappedNode == nodeNames[i] {
                    z += 1
                    player[i]!.zPosition = CGFloat(z)
                    print(player[i]!.zPosition)
                    player[i]!.position = pointOfTouch
                }
            }

        }

不要进行缓慢的搜索,而是为您接触的节点设置一个特殊的节点变量

class GameScene
{
    var touchedNodeHolder : SKNode?

    override func touchesBegan(.....)
    {
        for touch in touches {
            guard touchNodeHandler != nil else {return} //let's not allow other touches to interfere
            let pointOfTouch = touch.location(in: self)
            touchedNodeHolder = nodeAtPoint(pointOfTouch)
        }
    }
    override func touchesMoved(.....)
    {
        for touch in touches {

            let pointOfTouch = touch.location(in: self)
            touchedNodeHolder?.position = pointOfTouch
        }
    }
    override func touchesEnded(.....)
    {
        for touch in touches {

            touchedNodeHolder = nil
        }
    }
}