簡體   English   中英

在使用Swift的SpriteKit中,如何設置子節點數量的特定限制?

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

我有一個簡單的場景,一旦用戶觸摸某個區域,該場景就會向場景中添加一個彈跳球。 我們的目標是從別針彈跳球,以便在特定區域“得分”。

我只是對應用程序進行編碼的開始,但是我還找不到一種方法來限制用戶可以產生的球的數量。 目前,它們可以產生任意數量的球並使場景過飽和,從而導致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 */

}

我知道我需要詢問場景中場景中有多少個球節點,然后在達到極限時將其刪除,但是我嘗試嘗試的所有操作都會導致錯誤。

有很多方法可以做到這一點,但這可能是最簡單的。 注意:除非您在某個時候將球從場景中移開,否則您將達到10個球的極限並被卡住。

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)

        }

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM