-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBillboardComponent.swift
46 lines (39 loc) · 1.43 KB
/
BillboardComponent.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// BillboardComponent.swift
import ARKit
import RealityKit
import SwiftUI
public struct BillboardComponent: Component, Codable {
public init() {}
}
public struct BillboardSystem: System {
static let query = EntityQuery(where: .has(BillboardComponent.self))
private let arkitSession = ARKitSession()
private let worldTrackingProvider = WorldTrackingProvider()
public init(scene: RealityKit.Scene) {
setUpSession()
}
func setUpSession() {
Task {
do {
try await arkitSession.run([worldTrackingProvider])
} catch {
print("Error: \(error)")
}
}
}
public func update(context: SceneUpdateContext) {
let entities = context.scene.performQuery(Self.query).map({ $0 })
guard !entities.isEmpty,
let deviceAnchor = worldTrackingProvider.queryDeviceAnchor(atTimestamp:
CACurrentMediaTime()) else { return }
let cameraTransform = Transform(matrix: deviceAnchor.originFromAnchorTransform)
for entity in entities {
let translation = entity.transform.translation
entity.look(at: cameraTransform.translation,
from: entity.position(relativeTo: nil),
relativeTo: nil,
forward: .positiveZ)
entity.transform.translation = translation
}
}
}