问题描述
如何使用RealityKit跟踪摄像机的位置?几个示例都在使用SceneKit,但我发现没有一个在使用RealityKit.我需要一个功能,例如:
How can you track the position of the camera using RealityKit? Several examples are using SceneKit, but I found none using RealityKit. I need a function such as:
func session(_ session: ARSession, didUpdate frame: ARFrame) {
// Do something with the new transform
let currentTransform = frame.camera.transform
doSomething(with: currentTransform)
}
推荐答案
使用ARView Camera Transform:
您可以使用以下方法访问ARView Camera Transform:
You can access the ARView Camera Transform using the following method:
var cameraTransform: Transform
因此,假设您的ARView
被称为arView
,您可以像这样访问Transform
:
So assuming your ARView
was called arView
you could access the Transform
like so:
let cameraTransform = arView.cameraTransform
但是,更有用的实现方式是使您的ARView
通过使用以下内容来观察SceneEvents.Update
:
A more useful implementation however would be to enable your ARView
to observe SceneEvents.Update
by making use of the following:
subscribe(to:on:_:)
func subscribe<E>(to event: E.Type, on sourceObject: EventSource? = nil, _ handler: @escaping (E) -> Void) -> Cancellable where E : Event
这意味着您将拥有以下任何一个的观察者:
Which means you would have an observer of any:
为此,您将:首先导入Combine
框架.
To do that you would:Firstly import the Combine
Framework.
然后您将创建一个Cancellable
变量:
You would then create a Cancellable
variable:
var sceneObserver: Cancellable!
然后在ViewDidLoad
中添加如下内容:
Then in ViewDidLoad
add something like the following:
sceneObserver = arView.scene.subscribe(to: SceneEvents.Update.self) { [unowned self] in self.updateScene(on: $0) }
因此,每次更新都将调用以下内容:
Whereby each update calls the following:
/// Callback For ARView Update Events
/// - Parameter event: SceneEvents.Update
func updateScene(on event: SceneEvents.Update) {
print(arView.cameraTransform)
}
使用ARSessionDelegate:
或者,您也可以通过订阅ARSessionDelegate
例如在RealityKit
中访问ARCamera
:
Alternatively you can access the ARCamera
from within RealityKit
by subscribing to the ARSessionDelegate
e.g:
arView.session.delegate = self
然后注册以下回调:
func session(_ session: ARSession, didUpdate frame: ARFrame)
一个有效的示例看起来像这样:
Whereby a working example would look something like this:
extension ViewController: ARSessionDelegate {
func session(_ session: ARSession, didUpdate frame: ARFrame) {
guard let arCamera = session.currentFrame?.camera else { return }
print("""
ARCamera Transform = \(arCamera.transform)
ARCamera ProjectionMatrix = \(arCamera.projectionMatrix)
ARCamera EulerAngles = \(arCamera.eulerAngles)
""")
}
}
希望它会为您指明正确的方向.
Hope it points you in the right direction.
这篇关于使用RealityKit跟踪相机位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!