在使用enumerateChildNodesWithName后,我如何只让一个孩子做某事?

时间:2016-04-24 03:21:17

标签: swift sprite-kit game-physics enumerate

我使用enumerateChildNodesWithName命令给出了我的所有块物理,如下所示:

    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
            } 
        }
    }

现在我只希望其中一个块在被激光击中时消失。但是,如果没有让所有其他块同时消失,我就无法做到这一点 我试图在didBeginContact中使用这行代码来查找哪个块代表第一个主体并将其删除:

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])

    }

但这也结果不起作用。 请帮忙!提前谢谢!

1 个答案:

答案 0 :(得分:0)

我假设你应该处理联系人,以便你提供的if阻止正常工作。如果是这样,这就是你想要的:

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])
    }

}