Applying Force in User's Direction

I have the following code that creates a SCNBox and shoots it on the screen. This works but as soon as I turn the phone in any other direction then the force impulse does not get updated and it always shoots the box in the same old position.


Here is the code:


@objc func tapped(recognizer :UIGestureRecognizer) {
      
        guard let currentFrame = self.sceneView.session.currentFrame else {
            return
        }
      
        /
        let box = SCNBox(width: 0.2, height: 0.2, length: 0.2, chamferRadius: 0)
      
        let material = SCNMaterial()
        material.diffuse.contents = UIColor.red
        material.lightingModel = .constant
      
        var translation = matrix_identity_float4x4
        translation.columns.3.z = -0.01
      
        let node = SCNNode()
        node.geometry = box
        node.geometry?.materials = [material]
      
        print(currentFrame.camera.transform)
      
        node.physicsBody = SCNPhysicsBody(type: .dynamic, shape: nil)
      
        node.simdTransform = matrix_multiply(currentFrame.camera.transform, translation)
        node.physicsBody?.applyForce(SCNVector3(0,2,-10), asImpulse: true)
      
        self.sceneView.scene.rootNode.addChildNode(node)
      
      
    }



Line 26 is where I apply the force but it does not take into account the user's current phone orientation. How can I fix that?

You can try using ARCamera's eulerAngles attribute. It represent's the orientation of the user's camera. Coordinate the box and the force to the same direction the user's camera is facing. If you only want the object to follow the camera when the user is turning horizontal, then use "yaw" attribute when in portrait mode, and "pitch" attribute when in landscape mode. Use both attributes if you want the box to follow the camera anywhere.

Thanks! How will it change the code?


I have the following now:


let angle = currentFrame.camera.eulerAngles
        let forceAngle = SCNVector3FromFloat3(angle)
       
        node.simdTransform = matrix_multiply(currentFrame.camera.transform, translation)
       
        node.physicsBody?.applyForce(SCNVector3(forceAngle.x+0,forceAngle.y+0.2,-0.5), asImpulse: true)
Applying Force in User's Direction
 
 
Q