ARKit - Applying Force in User's Phone Direction

徘徊边缘 提交于 2019-12-19 10:18:03

问题


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?


回答1:


On line 26 you're passing a constant vector to applyForce. That method takes a vector in world space, so passing a constant vector means you're always applying a force in the same direction — if you want a direction that's based on the direction the camera or something else is pointing, you'll need to calculate a vector based on that direction.

The (new) SCNNode property worldFront might prove helpful here — it gives you the direction a node is pointing, automatically converted to world space, so it's useful with physics methods. (Though you might want to scale it.)



来源:https://stackoverflow.com/questions/44610512/arkit-applying-force-in-users-phone-direction

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!