ARKit计算从墙壁到相机的距离

时间:2018-06-29 17:19:18

标签: arkit

我正在使用ARKit开发一个项目。我想计算从墙壁到相机的距离,并且在我移开或移近时会更新。

现在,我已激活它可以检测水平和垂直表面。当我得到一个表面时,我会计算出从相机位置到表面中心的距离。应用微积分后,它将获得3D空间(欧几里得)中2个点之间的距离。  https://math.stackexchange.com/questions/42640/calculate-distance-in-3d-space

对吗?你能帮我吗?

class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate {

    let configuration = ARWorldTrackingConfiguration()

    override func viewDidAppear(_ animated: Bool) {
      super.viewDidAppear(animated)
      configuration.planeDetection = [.horizontal, .vertical]
      sceneView.session.run(configuration)
      ......
    }

    func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
      guard let planeAnchor = anchor as? ARPlaneAnchor else { return }
      let plane = SCNPlane(width: CGFloat(planeAnchor.extent.x), height: 
      CGFloat(planeAnchor.extent.z))
      let planeNode = SCNNode(geometry: plane)
      planeNode.simdPosition = float3(planeAnchor.center.x, 0, 
      planeAnchor.center.z)
      planeNode.eulerAngles.x = -.pi / 2   
      node.addChildNode(planeNode)
      let distance = distanceFromCamera(x: planeAnchor.center.x, y: 0, z: planeAnchor.center.z)
      let formatted = String(format: "Distance: %.2f", distance)
      print(formatted) q 
    }

    private func distanceFromCamera(x: Float, y:Float, z:Float) -> Float {
            let cameraPosition =  self.sceneView.session.currentFrame!.camera.transform.columns.3
            print("Camera: \(cameraPosition)")
            let vector = SCNVector3Make(cameraPosition.x - x, cameraPosition.y - y, cameraPosition.z - z)

            // Scene units map to meters in ARKit.
            return sqrtf(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z)
        }
}

1 个答案:

答案 0 :(得分:0)

添加以下方法

func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
    guard let currentBall = self.currentBall else {return}

    DispatchQueue.main.async {
        if let centerPosition = self.hitTestCenterVector() {
            let startPositionOfBall = currentBall.position
            let distance = self.getDistanceBetween(vector1: centerPosition, vector2: startPositionOfBall)
            self.lblDistance.text = String(format: "%.1f", distance) //meter
        }
    }
}

只需将保护声明中的self.currentBall替换为您要进行校准的SCNNode。距离

现在这是用于计算的方法

func hitTestCenterVector () -> SCNVector3? {
    let results =  self.sceneView.hitTest(self.sceneView.center, types: .existingPlane)

    if let firstObject = results.first  {
        return SCNVector3(firstObject.worldTransform.columns.3.x, firstObject.worldTransform.columns.3.y, firstObject.worldTransform.columns.3.z)
    }

    return nil
}


func getDistanceBetween(vector1:SCNVector3, vector2:SCNVector3) -> CGFloat {
   return  CGFloat(sqrt((vector1.x - vector2.x) * (vector1.x - vector2.x)
     + (vector1.y - vector2.y) * (vector1.y - vector2.y)
    + (vector1.z - vector2.z) * (vector1.z - vector2.z)))
}

希望对您有帮助