Implementing passingTest that returns all nodes in the node’s subtree that satisfy a test

Viewed 751

I am not really sure how to really use this function. I searched the internet thoroughly but could not find an instance of an example of this function being used. In SceneKit, I am pretty familiar with the function that searches by the node's name.. but this one is confusing since it returns a reference to a bool, that specifies an array.. The definition goes like this

func childNodes(passingTest predicate: (SCNNode, UnsafeMutablePointer<ObjCBool>) -> Bool) -> [SCNNode]

I got up to this point.. which gives me ALL the nodes I do not know why..

let ballToDisappear = sceneView?.scene.rootNode.childNodes(passingTest: { (node, ballYesOrNo) -> Bool in
        if (node.position.x < (maxVector?.x)! && node.position.x > (minVector?.x)!){
            if (node.position.y < (maxVector?.y)! && node.position.y > (minVector?.y)!){
                if (node.position.z < (maxVector?.z)! && node.position.z > (minVector?.z)!){
                    return ballYesOrNo.pointee.boolValue
                }
            }
        }
                    return !ballYesOrNo.pointee.boolValue
    }
    )

Any help would be greatly appreciated! Thanks!

1 Answers

The definition of childNodes(passingTest:) expects a closure that takes two arguments and returns a Bool. The arguments to the closure are:

  • child => the node to check (called node by you)
  • stop => indicates to stop the test. Calling this ballYesOrNo as you did is inherently confusing, better name it stop as the documentation suggests.

So you'd have to modify stop if and only if you want to stop the algorithm. You'd never want to return the value of stop directly.

To say that a child node matches, you have to return true, else false. Therefore:

let ballToDisappear = sceneView?.scene.rootNode.childNodes(passingTest: { (node, stop) -> Bool in
    if (node.position.x < (maxVector?.x)! && node.position.x > (minVector?.x)!){
        if (node.position.y < (maxVector?.y)! && node.position.y > (minVector?.y)!){
            if (node.position.z < (maxVector?.z)! && node.position.z > (minVector?.z)!){
                return false // or false here and true below??
            }
        }
    }
                return true // or true here, see above, depends on your logic
}
)
Related