Search code examples
swiftsprite-kitgame-physicsenumerate

How do I only make one child do something after using enumerateChildNodesWithName?


I used the enumerateChildNodesWithName command to give all of my blocks physics, like so:

    func findBlock(theName:String){

        self.enumerateChildNodesWithName("//*"){
        node, stop in

            if node.name == theName{
                node.physicsBody?.categoryBitMask = physicsCategory.block
                node.physicsBody?.collisionBitMask = physicsCategory.laser
                node.physicsBody?.contactTestBitMask = physicsCategory.laser
            } 
        }
    }

And now I want only one of the blocks to disappear when it gets hit by a laser. However, I haven't been able to make that happen without making all of the other blocks disappear at the same time.
I tried to use this line of code in didBeginContact to find which block represents the first body and remove it:

if firstBody.categoryBitMask == physicsCategory.block && secondBody.categoryBitMask == physicsCategory.laser{

        let block = SKSpriteNode()
        block.physicsBody = firstBody
        block.alpha = 1
        let byeBlock = SKAction.fadeOutWithDuration(0.5)
        let gone = SKAction.removeFromParent()
        let run = SKAction.sequence([byeBlock, gone])
        block.runAction(run)
        self.removeChildrenInArray([laser])

    }

but that also ended up not working. Please help! Thanks in advance!


Solution

  • I assume that you handle contacts as it should, so that if block you provided works correctly. If so, this is what you want :

    if firstBody.categoryBitMask == physicsCategory.block && secondBody.categoryBitMask == physicsCategory.laser{
    {
        //Downcast it to SKSpriteNode or whatever your block is
        if let block = firstBody.node as? SKSpriteNode {
    
            //We don't want to run removing action twice on the same block
            if block.actionForKey("removing") == nil {
    
                block.alpha = 1
                let fadeOut = SKAction.fadeOutWithDuration(0.5)
                let remove = SKAction.removeFromParent()
                block.runAction(SKAction.sequence([fadeOut, remove]), withKey: "removing")
            }
    
        }
        //Downcast it to SKSpriteNode or whatever your laser is
        if let laser = secondBody.node as? SKSpriteNode {
            self.removeChildrenInArray([laser])
        }
    
    }