【问题标题】:Place Node in ARKit World at touch location将节点放置在 ARKit World 中的触摸位置
【发布时间】:2019-12-24 18:45:32
【问题描述】:

我想在距离用户相机 10 厘米的地方放置一个节点。该节点应放置在用户触摸屏幕的位置(未投影)。但不幸的是,我的代码不起作用。您知道缺少什么吗?我该怎么办?

这是我的代码:

func getDirection(for point: CGPoint, in view: SCNView) -> SCNVector3 {
        let farPoint  = view.unprojectPoint(SCNVector3Make(Float(point.x), Float(point.y), -0.1))
        let nearPoint = view.unprojectPoint(SCNVector3Make(Float(point.x), Float(point.y), 0))

        return SCNVector3Make(farPoint.x - nearPoint.x, farPoint.y - nearPoint.y, farPoint.z - nearPoint.z)
    }

【问题讨论】:

标签: ios swift scenekit arkit


【解决方案1】:

1.首先添加一个点击手势识别器:

    func addTapGestureToSceneView() {
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didReceiveTapGesture(_:)))
        sceneView.addGestureRecognizer(tapGestureRecognizer)
    }

    func didReceiveTapGesture(_ sender: UITapGestureRecognizer) {
        let location = sender.location(in: sceneView)
        guard let hitTestResult = sceneView.hitTest(location, types: [.featurePoint, .estimatedHorizontalPlane]).first
            else { return }
        let anchor = ARAnchor(transform: hitTestResult.worldTransform)
        sceneView.session.add(anchor: anchor)
    }

2。实现 ARSCNViewDelegate :

extension ViewController: ARSCNViewDelegate {

    func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
        guard !(anchor is ARPlaneAnchor) else { return }
        let sphereNode = generateSphereNode()
        DispatchQueue.main.async {
            node.addChildNode(sphereNode)
        }
    }
}

    func generateSphereNode() -> SCNNode {
        let node = SCNNode(geometry: SCNSphere(radius: 0.05))
        node.geometry?.firstMaterial?.diffuse.contents = UIColor.blue
        return node
    }

【讨论】:

  • 要让你的 hitTest 工作,必须有一个距离相机 10 厘米的物体,hitTest 将为此返回一个 SCNVector3 值,否则你的 hitTest 结果将返回一个空数组或 hitResult 在最近的飞机。我评论中的答案处理了这个确切的问题。
猜你喜欢
  • 2018-01-11
  • 1970-01-01
  • 2018-06-22
  • 1970-01-01
  • 2018-12-01
  • 1970-01-01
  • 2013-03-08
  • 2018-12-02
  • 1970-01-01
相关资源
最近更新 更多