我正在用ARKit做实验,并试图在用户周围放置一些模型。所以我想要的是,当应用程序启动时,它只是在用户周围放置一些模型,所以他需要找到它们。
例如,当他移动到10米时,我想再添加一些随机模型。我想我可以这样做:
let cameraTransform = self.sceneView.session.currentFrame?.camera.transform
let cameraCoordinates = MDLTransform(matrix: cameraTransform!)
let camX = CGFloat(cameraCoordinates.translation.x)
let camY = CGFloat(cameraCoordinates.translation.y)
let cameraPosition = CGPoint(x: camX, y: camY)
let anchors = self.sceneView.hitTest(cameraPosition, types: [.featurePoint, .estimatedHorizontalPlane])
if let hit = anchors.first {
let hitTransform = SCNMatrix4(hit.worldTransform)
let hitPosition = SCNVector3Make(hitTransform.m41, hitTransform.m42, hitTransform.m43)
self.sceneView.session.add(anchor: ARAnchor(transform: hit.worldTransform))
return Coordinate(hitPosition.x, hitPosition.y, hitPosition.z)
}
return Coordinate(0, 0, 0)
}问题是有时它找不到锚,然后我不知道该怎么做。当它发现一些锚,它被随机地放在我身后,不是在我前面,而是在我身后。我不知道为什么,因为永远不要转动相机,这样它就找不到锚了。
有没有更好的方法在现实世界中放置随机模型?
发布于 2017-07-19 16:39:21
要做到这一点,您需要使用::didUpdate:)委托方法:
func session(_ session: ARSession, didUpdate frame: ARFrame) {
guard let cameraTransform = session.currentFrame?.camera.transform else { return }
let cameraPosition = SCNVector3(
/* At this moment you could be sure, that camera properly oriented in world coordinates */
cameraTransform.columns.3.x,
cameraTransform.columns.3.y,
cameraTransform.columns.3.z
)
/* Now you have cameraPosition with x,y,z coordinates and you can calculate distance between those to points */
let randomPoint = CGPoint(
/* Here you can make random point for hitTest. */
x: CGFloat(arc4random()) / CGFloat(UInt32.max),
y: CGFloat(arc4random()) / CGFloat(UInt32.max)
)
guard let testResult = frame.hitTest(randomPoint, types: .featurePoint).first else { return }
let objectPoint = SCNVector3(
/* Converting 4x4 matrix into x,y,z point */
testResult.worldTransform.columns.3.x,
testResult.worldTransform.columns.3.y,
testResult.worldTransform.columns.3.z
)
/* do whatever you need with this object point */
}它允许您在相机位置更新时放置对象:
如果您为呈现AR体验提供自己的显示,则实现此方法。提供的ARFrame对象包含从设备摄像机中捕获的最新图像,您可以将其呈现为场景背景,以及有关照相机参数和锚点转换的信息,这些信息可用于在摄像机图像之上呈现虚拟内容。
重要的在这里,你在随机地为hitTest方法选择点,这个点总是在摄像机前面。
不要忘记在CGPoint中使用从0到1.0的坐标系hitTest法
归一化图像坐标空间中的一点。(点(0,0)表示图像的左上角,点(1,1)表示右下角。
如果您想每隔10米放置一个物体,您可以保存相机位置(在session(_:didUpdate:)方法中),并检查x+z坐标是否有足够大的变化,以放置新对象。
注:
我假设您使用的是世界跟踪会话:
let configuration = ARWorldTrackingSessionConfiguration()
session.run(configuration, options: [.resetTracking, .removeExistingAnchors])https://stackoverflow.com/questions/45193078
复制相似问题