SceneKit:基于CoreMotion的相机移动

时间:2017-12-27 00:33:24

标签: ios swift scenekit core-motion scncamera

我试图模仿ARKit但是使用设备的前置摄像头而不是后置摄像头(并且不限于iPhone X)。到目前为止,我已经成功设置了一个简单的场景,只需在SCNCamera前面加载一个3D模型,并且感谢Travis在this answer提供的片段,根据设备的态度设法定位SCNCamera。

但是,我仍然需要根据设备的移动来翻译相机,这样我就可以从不同角度观察物体并“缩放”它;我无法弄清楚我应该使用哪些数据。是来自userAcceleration对象的CMDeviceMotion吗?我注意到,通过记录,即使我保持设备相对安静,我也会为加速度的组件获得一些非零值。关于如何处理这个问题的任何暗示或领导都是非常感激的。

这是我到目前为止的基本代码:

class ViewController: UIViewController {
    @IBOutlet weak var sceneView: SCNView!
    private let cameraNode = SCNNode()
    private var ringNode: SCNNode!
    private let motionManager = CMMotionManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        setupScene()
        setupMotionManager()
    }

    private func setupScene() {
        let objScene = SCNScene(named: "art.scnassets/ring.obj")!
        ringNode = objScene.rootNode.childNode(withName: "ring", recursively: true)
        ringNode.applyUniformScale(0.003)
        ringNode.position = SCNVector3(x: 0, y: 0, z: -5)

        let scene = SCNScene()
        scene.rootNode.addChildNode(ringNode)

        // create and add a camera to the scene
        cameraNode.camera = SCNCamera()
        scene.rootNode.addChildNode(cameraNode)

        // place the camera
        cameraNode.position = SCNVector3(x: 0, y: 0, z: 0)

        // create and add a light to the scene
        let lightNode = SCNNode()
        lightNode.light = SCNLight()
        lightNode.light!.type = .omni
        lightNode.position = SCNVector3(x: 0, y: 10, z: 10)
        scene.rootNode.addChildNode(lightNode)

        // create and add an ambient light to the scene
        let ambientLightNode = SCNNode()
        ambientLightNode.light = SCNLight()
        ambientLightNode.light!.type = .ambient
        ambientLightNode.light!.color = UIColor.darkGray
        scene.rootNode.addChildNode(ambientLightNode)          
        sceneView.scene = scene
    }

    private func setupMotionManager() {
        if motionManager.isDeviceMotionAvailable {
            motionManager.deviceMotionUpdateInterval = 1.0 / 60.0
            motionManager.startDeviceMotionUpdates(to: OperationQueue(), withHandler: { (motion, error) in
                if let motion = motion {
                    self.cameraNode.orientation = motion.gaze(atOrientation: .portrait)
                    let acc = motion.userAcceleration
                    print("Acc: \(accDescription(acc))")
                }
            })
        }
    }

0 个答案:

没有答案