enumerateChildNodes是否通过孙子进行排序?

时间:2018-06-07 18:17:14

标签: swift sprite-kit

我只是使用enumerateChildNodes来检查SKSpriteNodes是否相交,而不是使用物理主体来检测冲突。当SKSpriteNodes都是场景的子节点时,它对我很有用,但当其中一个SKSpriteNodes是孙子时它不起作用。我已经尝试在SKSpriteNode的名称之前使用//和/来搜索所有树,但它没有帮助。这是我的代码:

override func didMove(to view: SKView) {

    let red = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake(10,10))
    red.name = "red"
    self.addChild(red)

    let blue = SKSpriteNode(color: UIColor.blueColor(), size: CGSizeMake(10,10))
    blue.name = "blue"
    self.addChild(blue)

    let green = SKSpriteNode(color: UIColor.greenColor(), size: CGSizeMake(10,10))
    green.name = "green"
    blue.addChild(green)

}
override func update(_ currentTime: TimeInterval) {

    enumerateChildNodes(withName:"red") {node, _ in 
        let red = node as! SKSpriteNode
        if red.frame.intersects((self.childNode(withName:"//blue/green")?.frame)!) 
            { 
             red.removeFromParent() 
            }

}

2 个答案:

答案 0 :(得分:0)

为什么不在进行检查时引用蓝色的孩子,而不是在所有层次结构中循环

if red.frame.intersects((blue.childNode(withName: "green")?.frame)!) { 
    red.removeFromParent() 
}

答案 1 :(得分:0)

这里有一些问题,你想要双重枚举,你需要转换你的框架。

以下代码应该处理这个问题,但我没有测试准确性:

override func update(_ currentTime: TimeInterval) {
    var nodesToDelete = [SKNode]()
    enumerateChildNodes(withName:"red") {node, _ in 
        let red = node as! SKSpriteNode
        enumerateChildNodes(withName:"//blue/green") {node, killMe in 
            let green = node as! SKSpriteNode
            let point = green.parent!.convert(green.position, to:red.parent!)
            let convertedFrame = CGRect(origin:point:size:green.size)
            if red.frame.intersects(convertedFrame){ 
                nodesToDelete.append(red) 
                killMe.initialize(to: true) //stops enumeration of green
            }
        }
    }
    nodesToDelete.forEach{$0.removeFromParent()}
}