Suppose I have a collada file which has a box in it and I import the dae file into the scene. Now after importing in the scene I know the dae object is a box. How can I get the dimensions of the box in scenekit after adding it to the scene
If I import the node as a SCNBox i get errors saying that SNCBox is not a subtype of SCNNode.
floorNode = scene.rootNode.childNodeWithName("floor", recursively: false) as SCNBox
floorNode?.physicsBody = SCNPhysicsBody.staticBody()
floorNode?.physicsBody?.categoryBitMask = 2
let floorGeo: SCNBox = floorNode.geometry! as SCNBox
How do I get the dimensions if SCNNode is the only way to import nodes?
SCNBox is just helper subclass of SCNGeometry for box geometry creation. When you import Collada into a scene, you get scene graph of SCNNodes with SCNGeometries, not SCNBox'es or SCNCones etc doesn't matter how they look. If you want to get dimensions of any node you should use SCNBoundingVolume
protocol, which is implemented by both SCNNode and SCNGeometry classes:
func getBoundingBoxMin(_ min: UnsafeMutablePointer, max max: UnsafeMutablePointer) -> Bool
With this method you will get bounding box corners. For box-shaped geometry, dimensions will match bounding box.
Example:
var v1 = SCNVector3(x:0, y:0, z:0)
var v2 = SCNVector3(x:0, y:0, z:0)
node.getBoundingBoxMin(&v1, max:&v2)
Where node is node you want to get bounding box of. Results will be in v1 and v2.
Swift 3
Using Swift 3 you can simply use node.boundingBox.min
and node.boundingBox.max
respectively.
Example Swift code on how to use boundingBox
:
var min = shipNode.boundingBox.min
var max = shipNode.boundingBox.max
let w = CGFloat(max.x - min.x)
let h = CGFloat(max.y - min.y)
let l = CGFloat(max.z - min.z)
let boxShape = SCNBox (width: w , height: h , length: l, chamferRadius: 0.0)
let shape = SCNPhysicsShape(geometry: boxShape, options: nil)
shipNode.physicsBody!.physicsShape = SCNPhysicsShape(geometry: boxShape, options: nil)
shipNode.physicsBody = SCNPhysicsBody.dynamic()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With