在使用 Swift 的 SpriteKit 中,如何设置子节点数量的特定限制?

In SpriteKit using Swift how can you set a specific limit for the amount of child nodes?

我有一个简单的场景,当用户触摸某个区域时,它会在场景中添加一个弹跳球。目标是将球从别针上弹开,以便 'score' 在特定区域。

我刚刚开始编写应用程序代码,但我还无法找到一种方法来限制用户可以生成的球数量。目前,他们可以生成任意数量的球并使场景过度饱和,从而导致 FPS 下降和非常简单的游戏!

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    /* Called when a touch begins */

    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)

        let ball = SKSpriteNode(imageNamed:"ball")

        ball.xScale = 0.2
        ball.yScale = 0.2
        ball.position = location

        ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height / 2.0)
        ball.physicsBody!.dynamic = true

        ball.physicsBody!.friction = 0
        ball.physicsBody!.restitution = 0.8

        ball.name = "ball"

        self.addChild(ball)

    }
}

override func update(currentTime: CFTimeInterval) {
    /* Called before each frame is rendered */

}

我知道我需要询问场景场景中有多少个球节点,然后在球达到极限后将其移除,但我似乎尝试的所有操作都会导致错误。

有很多方法可以做到这一点,但这可能是最简单的。 注意:除非你在某个时候从场景中移除球,否则你将达到十个球的限制并卡住。

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    /* Called when a touch begins */

    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)

        // ball limit
        let limit = 10

        // setup counter
        var i = 0

        // loop through the ball nodes added to the scene
        self.enumerateChildNodesWithName("ball", usingBlock: {
            _, _ in  // we dont need to use these variables right now   
            i += 1  // increment the counter
        })

        // if we haven't hit our limit, add a ball (YOUR CODE HERE)
        if i <= limit {

            let ball = SKSpriteNode(imageNamed:"ball")

            ball.xScale = 0.2
            ball.yScale = 0.2
            ball.position = location

            ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height / 2.0)
            ball.physicsBody!.dynamic = true

            ball.physicsBody!.friction = 0
            ball.physicsBody!.restitution = 0.8

            ball.name = "ball"

            self.addChild(ball)

        }

    }
}