在ARKit 1.5

时间:2018-04-25 05:45:59

标签: swift arkit

我略微修改了Apple's example关于识别ARKit 1.5中的图像,以便每次识别图像时都会在其前面显示一些文本几何体。

不幸的是我发现当按下StatusView视图中的重置按钮时,我的文本几何体不会被删除,而只会在场景的新中心周围重新定位。

相反,如果我按下后退按钮(因为我将主视图控制器嵌入导航控制器中以便通过按钮启动AR会话而不是像示例中那样自动启动AR会话),然后再次启动会话,然后一切都正确消失。

分析代码我可以确认重置按钮和来自ViewController的来回触发相同的功能如下

func resetTracking() {

    guard let referenceImages = loadImageReferences() else {
        fatalError("Missing expected asset catalog resources.")
    }

    let configuration = ARWorldTrackingConfiguration()
    configuration.detectionImages = referenceImages
    configuration.planeDetection = [.horizontal, .vertical]
    session.run(configuration, options: [.resetTracking, .removeExistingAnchors])

    statusViewController.scheduleMessage("Look around to detect images", inSeconds: 7.5, messageType: .contentPlacement)
}

正如我所提到的,此函数在ViewController的ViewDidLoad方法中调用

override func viewDidLoad() {
    super.viewDidLoad()

    sceneView.delegate = self
    sceneView.session.delegate = self

    // debug scene to see feature points and world's origin ARSCNDebugOptions.showFeaturePoints,
    self.sceneView.debugOptions = [ARSCNDebugOptions.showWorldOrigin]

    // Hook up status view controller callback(s).
    statusViewController.restartExperienceHandler = { [unowned self] in
        self.restartExperience()
    }   
}

func restartExperience() {
    guard isRestartAvailable else { return }
    isRestartAvailable = false

    statusViewController.cancelAllScheduledMessages()

    resetTracking()

    // Disable restart for a while in order to give the session time to restart.
    DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
        self.isRestartAvailable = true
    }
}

并按下StatusViewController中的重置按钮。

@IBAction private func restartExperience(_ sender: UIButton) {
    restartExperienceHandler()
}

var restartExperienceHandler: () -> Void = {}

为了进一步参考,我创建了如下文字

func createBillboardText(text: String, position: SCNNode, width: CGFloat, height: CGFloat){

    let newText = splitString(every: 10, string: text)
    let textGeometry = SCNText(string: newText, extrusionDepth: 1.0)

    textGeometry.firstMaterial!.diffuse.contents = UIColor.red
    let textNode = SCNNode(geometry: textGeometry)

    // Update object's pivot to its center
    // https://stackoverflow.com/questions/44828764/arkit-placing-an-scntext-at-a-particular-point-in-front-of-the-camera
    let (min, max) = textGeometry.boundingBox
    let dx = min.x + 0.5 * (max.x - min.x)
    let dy = min.y + 0.5 * (max.y - min.y)
    let dz = min.z + 0.5 * (max.z - min.z)
    textNode.pivot = SCNMatrix4MakeTranslation(dx, dy, dz)
    textNode.scale = SCNVector3(0.005, 0.005, 0.005)

    let plane = SCNPlane(width: width, height: height)
    let blueMaterial = SCNMaterial()
    blueMaterial.diffuse.contents = UIColor.blue
    blueMaterial.transparency = 0                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
    plane.firstMaterial = blueMaterial
    let parentNode = SCNNode(geometry: plane) // this node will hold our text node

    let yFreeConstraint = SCNBillboardConstraint()
    yFreeConstraint.freeAxes = [.Y] // optionally
    parentNode.constraints = [yFreeConstraint] // apply the constraint to the parent node

    parentNode.addChildNode(textNode)

    position.addChildNode(parentNode)

    sceneView.autoenablesDefaultLighting = true

}

func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor)方法中调用self.createBillboardText(text: message, position: node, width: referenceImage.physicalSize.width, height: referenceImage.physicalSize.height )

我还找到this thread,但我不知道如何在场景中调用该函数。

2 个答案:

答案 0 :(得分:2)

我相信您要处理删除SCNNodes的方式是在resetFunction中调用以下函数:

self.augmentedRealityView.scene.rootNode.enumerateChildNodes { (existingNode, _) in
    existingNode.removeFromParentNode()
}

其中augmentedRealityView指的是ARSCNView

您还可以将特定节点存储在[SCNNode]数组中,然后遍历它们以删除它们,例如:

for addedNode in nodesAdded{

addedNode.removeFromParentNode()

}

希望它有所帮助...

答案 1 :(得分:1)

如果要删除所有节点,请使用以下命令:

self.sceneView.scene.rootNode.enumerateChildNodes { (node, stop) in
    node.removeFromParentNode()
}

现在,如果要删除特定节点,请使用以下命令:

self.sceneView.scene.rootNode.enumerateChildNodes { (node, stop) in
        if node.name == "textNode" {
            node.removeFromParentNode()
        }
}

这些也适用于SCNNode,而不仅仅是ARSCNView,这意味着您可以将子节点循环到SCNNode,而不仅仅是来自场景rootNode

这是我在项目中使用的代码。在这里,我首先删除节点上的所有childNodes,然后删除SCNNode本身。然后我继续暂停会话,这将结束它。我运行新会话,最后将worldOrigin重置为当前摄像机位置。如果应用程序的启动角度关闭,形状可能会出错。

sceneView.scene.rootNode.enumerateHierarchy { (node, stop) in
       node.childNodes.forEach({
          $0.removeFromParentNode()
       })
       node.removeFromParentNode()
}
sceneView.session.pause()
sceneView.session.run(configuration, options: .resetTracking)
sceneView.session.setWorldOrigin(relativeTransform: matrix)