首页 > 解决方案 > Swift:使用场景包中的 projectPoint 随着时间的推移获取并保存更新的 SCNNode

问题描述

我正在尝试使用projectPoint在 scenekit 中获取更新的 SCNNode 的 2D 信息并保存它们。

根据 ignotusverum 的建议,我可以将 SCNNode 保存到按钮中的路径中。

     var lastPosition: CGPoint?
     func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
            guard anchor == currentFaceAnchor,
                let contentNode = selectedContentController.contentNode,
                contentNode.parent == node
                else { return }
            for (index, vertex) in vertices.enumerated() {
            let vertex = sceneView.projectPoint(node.convertPosition(SCNVector3(vertex), to: nil))
            let xVertex = CGFloat(vertex.x)
            let yVertex = CGFloat(vertex.y)
            Position = CGPoint(x: xVertex, y: yVertex)
           }
            selectedContentController.session = sceneView?.session
            selectedContentController.sceneView = sceneView
            selectedContentController.renderer(renderer, didUpdate: contentNode, for: anchor)
        }

通过开始按钮开始保存:

    private var fpsTimer = Timer()
    private var currentCaptureFrame = 0
    @IBAction private func startPressed() {
        currentCaptureFrame = 0 //inital capture frame
        fpsTimer = Timer.scheduledTimer(withTimeInterval: 1/fps, repeats: true, block: {(timer) -> Void in self.recordData()})
    }

通过单击停止按钮保存它们:

@IBAction private func stopPressed() {
    do {
        fpsTimer.invalidate() //turn off the timer
        let capturedData = captureData.map{$0.stringRepresentation}.joined(separator:"\(lastPosition)>")
        let dir: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last! as URL
        let url = dir.appendingPathComponent("testing.txt")
        try capturedData.appendLineToURL(fileURL: url as URL)
    }
    catch {
        print("Could not write to file")
    }
}

到目前为止,在保存点的情况下工作正常。问题是在保存的数据中,我意识到数据只保存了 x 和 y 顶点的一帧。例如:

[(411.0618591308594, 534.4215087890625), (410.7286071777344, 544.9381713867188), (411.5425720214844, 522.1063232421875), (412.0340881347656, 512.1854248046875),... 

[(411.0618591308594, 534.4215087890625), (410.7286071777344, 544.9381713867188), (411.5425720214844, 522.1063232421875), (412.0340881347656, 512.1854248046875)

从单击开始按钮到停止按钮的那一刻起,数据以一帧而不是我要保存的时间段重复。

我的问题是从我单击开始按钮到停止按钮的那一刻起,如何随着时间的推移保存更新的 SCNNode?

提前致谢!

标签: iosswiftaugmented-realityscenekitarkit

解决方案


SceneKit 每帧只调用一次此方法。如果你在渲染器中做一些事情,你必须“完成它”然后离开,否则它会对 FPS 产生影响。

如果您需要移动或检查大量循环内容,您可以使用计时器单独执行这些工作,这样您就可以对其进行一些控制。您仍然可以保持您的 FPS 并在计时器中中断循环或分块工作。如果你这样做,只要确保你把定时器放在主线程中。

您还可以查看:node.presentation,即:属性反映了由当前影响节点的任何飞行动画确定的临时值。


推荐阅读