Multi-touch gesture in Sprite Kit

前端 未结 1 395
逝去的感伤
逝去的感伤 2020-12-02 00:26

I\'m working in Swift with Sprite-Kit using XCode 6, and I have many different nodes but for the moment I only manage to detect one finger and move one node at the same time

相关标签:
1条回答
  • 2020-12-02 00:59

    Moving multiple nodes simultaneously is fairly straightforward. The key is to track each touch event independently. One way to do that is to maintain a dictionary that uses the touch event as the key and the node being moved as the value.

    First, declare the dictionary

    var selectedNodes:[UITouch:SKSpriteNode] = [:]
    

    Add each sprite touched to the dictionary with the touch event as the key

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let location = touch.location(in:self)
            if let node = self.atPoint(location) as? SKSpriteNode {
                // Assumes sprites are named "sprite"
                if (node.name == "sprite") {
                    selectedNodes[touch] = node
                }
            }
        }
    }
    

    Update the positions of the sprites as needed

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let location = touch.location(in:self)
            // Update the position of the sprites
            if let node = selectedNodes[touch] {
                node.position = location
            }
        }
    }
    

    Remove the sprite from the dictionary when the touch ends

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            if selectedNodes[touch] != nil {
                selectedNodes[touch] = nil
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题