Hunter
Hunter

Reputation: 117

How to position a SCNPhysicsBody at the center of a scnnode

I have a SCNNode and a full working physics body attached to it, but the physics bodies center/resting-point is at the bottom of the SCNNode.

Here's what I'm trying to do:

Apple Developer hasn't help me so far. Here is what I have:

let nodePhysicsBody = SCNPhysicsBody(type: .dynamic, shape: SCNPhysicsShape(geometry: SCNCapsule(capRadius: 2.0, height: 2.0), options: nil))

I found this init method, but I'm not sure if it will work, or how to implement it.

.init(circleOfRadius r: CGFloat, center: CGPoint()

Upvotes: 1

Views: 901

Answers (2)

rswayz
rswayz

Reputation: 1184

For a full example (my physics were centered about the base of my .dae animation, and I needed the physics body centered at the center of mass of the SCNNode):

// refNode is the SCNReferenceNode loaded from the .dae animation
 let kCharacterScale = SCNVector3(20.0,20.0,20.0)   //Set the node and physics scales
 let boundingBox = refNode.boundingBox
 let min = boundingBox.min
 let max = boundingBox.max
 let w = (max.x - min.x) 
 let h = (max.y - min.y) 
 let l = (max.z - min.z) 
 let boxShape = SCNBox (width: CGFloat(w) , height: CGFloat(h) , length: CGFloat(l), chamferRadius: 0.0)
 var shape = SCNPhysicsShape(geometry: boxShape, options: [SCNPhysicsShape.Option.scale : kCharacterScale, SCNPhysicsShape.Option.type : SCNPhysicsShape.ShapeType.boundingBox])
 let translate = SCNMatrix4MakeTranslation(0.0, (h*kCharacterScale.y/2.0), 0.0)
 let translateMatrix = NSValue.init(scnMatrix4: translate)
 shape = SCNPhysicsShape.init(shapes: [shape], transforms: [translateMatrix])
        refNode.physicsBody = SCNPhysicsBody(type: .kinematic, shape: shape)

Upvotes: 3

rickster
rickster

Reputation: 126167

I'd suggest trying the SCNPhysicsShape init(shapes:transforms:) initializer — rather than constructing a physics shape out of several shapes (and using the transforms parameter to position them relative to one another), you might be able to pass a single shape and a transform that offsets it from the center of the parent coordinate space.

Upvotes: 5

Related Questions