ARKit - 将“SCNNode”添加到“ARAnchor”

时间:2017-10-22 12:04:24

标签: scenekit augmented-reality arkit aranchor

我不确定我是否正确接近这一点。我有一个长矩形框,我想在应用程序启动时从相机中添加-1.5。但我希望它是静止的,就像在ARKit项目中默认出货的船一样。但每当我添加它时,物体与相机保持相对(远距离)。即 - 向它移动,向后移动,向后移动,向前移动。

我虽然在现场放下一个锚点会解决这个问题,但我仍然会受到同样的影响。这是我的代码。任何帮助将不胜感激:

override func viewDidLoad() {
    super.viewDidLoad()

    // Set the view's delegate
    sceneView.delegate = self

    // Show statistics such as fps and timing information
    //sceneView.showsStatistics = true

    // Create a new scene
    let scene = SCNScene()//

    // Set the scene to the view
    sceneView.scene = scene 
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // Create a session configuration
    let configuration = ARWorldTrackingConfiguration()

    //configuration.planeDetection = .horizontal

    // Run the view's session
    sceneView.session.run(configuration)

    print(#function, sceneView.session.currentFrame)
}

// MARK: - SCNSceneRendererDelegate
    func renderer(_ renderer: SCNSceneRenderer, didRenderScene scene: SCNScene, atTime time: TimeInterval) {
        print(#function, sceneView.session.currentFrame)

        if !hasPortalAnchor {

            //add anchor - this may take a second as the current frames are initially nil
            if let currentFrame = sceneView.session.currentFrame {
                var translation = matrix_identity_float4x4
                translation.columns.3.z = -1.3
                let transform = simd_mul(currentFrame.camera.transform, translation)

                if (arrAnchors.count < 1) {
                let portalAnchor = ARAnchor(transform: transform)
                sceneView.session.add(anchor: portalAnchor)
                arrAnchors.append(portalAnchor)
                print(arrAnchors)
                }
            }

        } else {
            hasPortalAnchor = true
        }          
    }

//this function gets called whenever we add an anchor to our scene
func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {

    let portalScene = SCNScene(named: "art.scnassets/portal.scn")! 
    return portalScene.rootNode.childNode(withName: "portal", recursively: true)   
}

1 个答案:

答案 0 :(得分:0)

您是否故意使用renderer(_:)功能?如果没有,那么您可以使用以下viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()

    sceneView.delegate = self

    let scene = SCNScene(named: "art.scnassets/portal.scn")!

    sceneView.scene = scene

}

这将替换启动时出现的门户场景的默认火箭。 (请注意,如果尚未建立跟踪,场景可能会移动。例如,如果灯光较低,或者您处于没有很多功能的环境中(例如,空白或重复的墙壁)。)

看起来你实际上并没有将hasPortalAnchor设置为true?它被设置在其他地方吗?