简体   繁体   中英

How do you get the count of specific nodes in SpriteKit?

I'm making an iOS game that involves shooting cannonballs out of a cannon. How can I get the number of cannons that are in the scene? Here's my function to create, shoot, and remove cannonballs (this function is called when the player taps the screen):

func fireCannonBall()
    {
        let cannonBall = SKSpriteNode(imageNamed: "cannonBall")
        cannonBall.position.x = //some x-position
        cannonBall.position.y = //some y-position
        cannonBall.zPosition = 1
        self.addChild(cannonBall)
        
        let moveCannonBall = SKAction.moveBy(x: cos(currentAngle) * 2400, y: sin(currentAngle) * 2400, duration: 3)
        let deleteCannonBall = SKAction.removeFromParent()
        let cannonSequence = SKAction.sequence([cannonSound, moveCannonBall, deleteCannonBall])
        cannonBall.run(cannonSequence)
    }

You can assign each cannon ball a name, like so cannonBall.name = "cannonBall"

You can then get all the cannon balls that are in the scene using the subscript(_:) or enumerateChildNodes(withName:using:) method.

Here is a reference to Apple's documentation: Searching the Node tree

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