SCNNode point inside test

520 views Asked by At

Given a SCNNode, how can I determine if a point (specified in the node's coordinate system) is contained inside that node's geometry?

Alternatively, if simpler, how can I test if a point is contained within the node's bounding box?

1

There are 1 answers

0
Benjohn On

I'd be surprised if there isn't a better answer than this, but I've not found one, so here's what I've got.

extension SCNNode {
  func boundingBoxContains(point: SCNVector3, in node: SCNNode) -> Bool {
    let localPoint = self.convertPosition(point, from: node)
    return boundingBoxContains(point: localPoint)
  }

  func boundingBoxContains(point: SCNVector3) -> Bool {
    return BoundingBox(self.boundingBox).contains(point)
  }
}

struct BoundingBox {
  let min: SCNVector3
  let max: SCNVector3

  init(_ boundTuple: (min: SCNVector3, max: SCNVector3)) {
    min = boundTuple.min
    max = boundTuple.max
  }

  func contains(_ point: SCNVector3) -> Bool {
    let contains =
    min.x <= point.x &&
    min.y <= point.y &&
    min.z <= point.z &&

    max.x > point.x &&
    max.y > point.y &&
    max.z > point.z

    return contains
  }
}