简体   繁体   中英

How to limit the number of touches in touchesBegan in swift Spritekit

I have written a location finder for touch points in my touchesBegan function, I want to limit the number of touch points allowed in the view controller to 2 but I don't quite know how to do that. A little help would be fantastic.

  override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
   for touch: AnyObject in touches {
    let location = touch.locationInNode(self)


    Object.physicsBody?.affectedByGravity = true
    Object2.physicsBody?.affectedByGravity = true
    Object3.physicsBody?.affectedByGravity = true


    if Object.containsPoint(location) {
  Object.physicsBody?.velocity = CGVectorMake(0, 0)
    Object.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 135))

}

        if Object2.containsPoint(location) {
           Object2.physicsBody?.velocity = CGVectorMake(0, 0)
            Object2.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 135))
 }


        if Object3.containsPoint(location) {
            Object3.physicsBody?.velocity = CGVectorMake(0, 0)
            Object3.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 135))



    }

    }


        }

As you see touches is a Set struct object, and it has a cardinality, in this case touches.count So the point is to find this cardinality, compare it to 2 and perform action only if it is less than or equal to 2 .

So it goes like this

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if touches.count <= 2 {
        for touch: AnyObject in touches {
            // do stuff
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM