Spiff
Spiff

Reputation: 903

Rotating and moving SCNNode in world space

I’m trying to rotate and move a SCNNode. It is acting as if I’m still rotating in local space rather than world space. If I rotate the item and then apply force, it moves in the same direction as before, just pointing in a new direction, rather than ‘forward’ being redefined by the rotation. What am I doing wrong? Thanks.

func applyForce(to node: SCNNode) {
    let newTransform = SCNMatrix4Translate(node.worldTransform, force.x, force.y, force.z)
    node.setWorldTransform(newTransform)
}
    
func applyRotation(to node: SCNNode, radians: Float) {
    let newTransform = SCNMatrix4Rotate(node.worldTransform, radians, 0, 1, 0)
    node.setWorldTransform(newTransform)
}

Upvotes: 0

Views: 259

Answers (1)

Spiff
Spiff

Reputation: 903

I've found an answer. I perform the rotation in local space and translate the node in world space. The nil argument in simdConvertVector converts to world. This accomplishes my goal.

```
func applyForce(_ force: SCNVector3, to node: SCNNode) {
        let force = SIMD3<Float>(force)
        let translation = SIMD3<Float>(1, 1, 1) * force
        let newPosition = node.simdConvertVector(translation, to: nil)
        node.simdPosition += newPosition
}

func applyRotation(_ radians: Float, to node: SCNNode) {
    let newTransform = SCNMatrix4Rotate(node.transform, radians, 0, 1, 0)
    node.transform = newTransform
}
```

Upvotes: 1

Related Questions