Kyle Decot Kyle Decot - 2 months ago 11x
iOS Question

Total height of SCNNode childNodes

I'm currently using the following to get the total height of all of the child nodes in a

. Is there a more efficient/better/shorter/more swift-like way to do this?

CGFloat(columnNode.childNodes.reduce(CGFloat()) {
let geometry = $1.geometry! as SCNBox
return $0 + geometry.height


Yes, and a way that'll get you a more correct answer, too. Summing the height of all the child nodes' geometries...

  • only works if the geometry is an SCNBox
  • doesn't account for the child nodes' transforms (what if they're moved, rotated or scaled?)
  • doesn't account for the parent node's transform (what if you want height in scene space?)

What you want is the SCNBoundingVolume protocol, which applies to all nodes and geometries, and describes the smallest rectangular or spherical space containing all of a node's (and its subnodes') content.

In Swift 3, this is super easy:

let (min, max) = columnNode.boundingBox

After this, min and max are the coordinates of the lower-rear-left and upper-front-right corners of the smallest possible box containing everything inside columnNode, no matter how that content is arranged (and what kind of geometry is involved). These coordinates are expressed in the same system as columnNode.position, so if the "height" you're looking for is in the y-axis direction of that space, just subtract the y-coordinates of those two vectors:

let height = max.y - min.y

In Swift 2, the syntax for it is a little weird, but it works well enough:

var min = SCNVector3Zero
var max = SCNVector3Zero
columnNode.getBoundingBoxMin(&min, max: &max)