如何使用ARKit将SCNNode的方向更改为相机

时间:2017-09-24 12:26:32

标签: ios arkit xcode9 scnnode

下面的代码将SCNPlane放置到触摸点上,但是平面朝向(旋转)到应用程序启动时手机所处的位置。理想情况下,我希望将节点定位到物理墙或相机的当前方向。这是如何用ARKit完成的?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let touch = touches.first else {return}
    let result = sceneView.hitTest(touch.location(in: sceneView), types: [ARHitTestResult.ResultType.featurePoint])
    guard let hitResult = result.last else {return}
    let hitTransform = SCNMatrix4.init(hitResult.worldTransform)

    let hitVector = SCNVector3Make(hitTransform.m41, hitTransform.m42, hitTransform.m43)
    createPlane(position: hitVector)
}

func createPlane(position: SCNVector3) {

    let background = SCNNode()
    background.geometry = SCNPlane.init(width: 0.12, height: 0.10) // better set its size
    background.geometry?.firstMaterial?.diffuse.contents = "odinBW2.jpeg"
    background.position = position

    sceneView.scene.rootNode.addChildNode(background)

}

1 个答案:

答案 0 :(得分:5)

1 - 这是您首先获得相机旋转的方式:

  

间距 - 围绕X轴旋转

let pitch = sceneView.session.currentFrame?.camera.eulerAngles.x 
  

打哈欠 - 围绕Y轴旋转

let yawn = sceneView.session.currentFrame?.camera.eulerAngles.y
  

滚动 - 围绕Z轴旋转

let roll = sceneView.session.currentFrame?.camera.eulerAngles.z

2 - 然后您可以创建与您要保留的旋转相匹配的SCNVector3(如果您不想在轴上进行任何旋转,则为0):

let newRotation = SCNVector3Make(pitch, yawn, roll)

3 - 然后将此eulerAngles归因于您的节点:

whateverNode.eulerAngles = newRotation