一次检测多个触摸(Swift)

时间:2016-04-17 03:22:20

标签: ios swift sprite-kit

我正在使用 Xcode 7,Swift和SpriteKit ,我试图允许用户在我的应用中一次使用两根手指。

基本上我的屏幕有两半,我希望每一方都有单独的触摸识别,并且同时

以下是我目前的代码:

    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?)
    {
        guard let touch = touches.first else {
            return;
        }
        let location = touch.locationInNode(self)
        let touchedNode = self.nodeAtPoint(location)
        if (touchedNode == touch1){
            //code1
        }
        else if (touchedNode == touch2){
            //code2
        }
    }

touch1和touch2是SkSpriteNodes,每个都占据屏幕的不同部分 只要您一次只有一根手指在屏幕上,此代码就可以正常工作 但是如果有两个(每半个1个),那么首先在屏幕上放置一个是注册的那个。

如何进行注册,因此正在运行code1和code2?

1 个答案:

答案 0 :(得分:1)

您需要将multipleTouchEnabled属性设置为true。来自有关此属性的文档:

  

当设置为YES时,接收器接收与a相关的所有触摸   多点触控序列。设置为NO时,接收器仅接收   多点触控序列中的第一个触摸事件。默认值   财产是NO。

修改

根据您的评论,您可以尝试这样做(让精灵对触摸做出响应):

class Button:SKSpriteNode {

    init(size:CGSize, color:SKColor) {

        super.init(texture: nil, color: color, size: size)

        userInteractionEnabled = true
    }

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

        if let name = self.name {
            print("Button with \(name) pressed")
        }
    }

    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if let name = self.name {
            print("Button with \(name) pressed")
        }
    }

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if let name = self.name {
            print("Button with \(name) released")
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

class GameScene: SKScene, SKPhysicsContactDelegate {

    override func didMoveToView(view: SKView) {

        let left = Button(size: CGSize(width: frame.size.width/2.0, height: frame.size.height), color: .blackColor())
        left.name = "left"
        left.position = CGPoint(x: left.size.width/2.0, y: frame.midY)

        let right = Button(size: CGSize(width: frame.size.width/2.0, height: frame.size.height), color: .whiteColor())
        right.name = "right"
        right.position = CGPoint(x:frame.maxX-right.size.width/2.0, y: frame.midY)

        addChild(left)
        addChild(right)

    }
}