使用SpriteKit一次移动多个节点

时间:2016-12-16 07:31:33

标签: sprite-kit touchesbegan touchesmoved

我的游戏有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正在移动,且nodeBnodeB的交叉路径跟随nodeA

如何设置,以便当用户移动时nodeAnodeA通过nodeB nodeB不会跟随nodeA

2 个答案:

答案 0 :(得分:5)

不是进行慢速搜索,而是为触摸的节点设置一个特殊的节点变量

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
        }
    }
}

答案 1 :(得分:1)

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

我没有通过触摸位置选择节点,而是发现通过名称属性选择节点就可以了。

显示的代码在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
                }
            }

        }