返回类型ARRaycastQuery?
最初是可选的
据苹果公司称文档 https://developer.apple.com/documentation/arkit/arscnview/3194595-raycastquery:
raycastQuery(from:allowing:alignment:)
实例方法创建一条从参数屏幕空间点沿 z 轴正方向延伸的射线,确定任何参数目标是否存在于沿着射线的物理环境中的任何位置。如果是这样,ARKit 将返回光线与目标相交的 3D 位置。
如果射线不与目标相交,则不存在ARRaycastQuery
目的。所以有nil
.
func raycastQuery(from point: CGPoint,
allowing target: ARRaycastQuery.Target,
alignment: ARRaycastQuery.TargetAlignment) -> ARRaycastQuery?
回国的两个可能原因是什么nil
?
Solution
您的代码可能如下所示:
@IBOutlet var sceneView: ARSCNView!
@IBAction func onTap(_ sender: UIGestureRecognizer) {
let tapLocation: CGPoint = sender.location(in: sceneView)
let estimatedPlane: ARRaycastQuery.Target = .estimatedPlane
let alignment: ARRaycastQuery.TargetAlignment = .any
let query: ARRaycastQuery? = sceneView.raycastQuery(from: tapLocation,
allowing: estimatedPlane,
alignment: alignment)
if let nonOptQuery: ARRaycastQuery = query {
let result: [ARRaycastResult] = sceneView.session.raycast(nonOptQuery)
guard let rayCast: ARRaycastResult = result.first
else { return }
self.loadGeometry(rayCast)
}
}
这是获取模型的方法:
func loadGeometry(_ result: ARRaycastResult) {
let scene = SCNScene(named: "art.scnassets/myScene.scn")!
let node: SCNNode? = scene.rootNode.childNode(withName: "model",
recursively: true)
node?.position = SCNVector3(result.worldTransform.columns.3.x,
result.worldTransform.columns.3.y,
result.worldTransform.columns.3.z)
self.sceneView.scene.rootNode.addChildNode(node!)
}