Moving multiple nodes at once from touch with SpriteKit

老子叫甜甜 提交于 2019-12-02 09:16:12

问题


I have a game that has 3 SKSpriteNodes that the user can move around using the touchesBegan and touchesMoved. However, when the users moves nodeA and passes another node called nodeB, nodeB follows nodeA and so on.

I created an array of SKSpriteNodes and used a for-loop to make life easier.

 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
                }

            }


        }

    }

Everything is working except when nodeA is moving and cross paths with nodeB, nodeB follows nodeA.

How can I make it so that when the user is moving nodeA and nodeA passes through nodeB that nodeB would not follow nodeA.


回答1:


Instead of doing slow searches, have a special node variable for your touched node

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



回答2:


After some experimenting, I found a way to go about this problem.

Instead of selecting the node by the position of the touch, I found that selecting the node by its name property did the trick.

The code shown is implemented inside the touchesMoved and touchesBegan methods

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

        }


来源:https://stackoverflow.com/questions/41179326/moving-multiple-nodes-at-once-from-touch-with-spritekit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!