Here is my code. I don't understand why it doesn't work, please help me
import SwiftUI
import RealityKit
import ARKit
import Combine
var character: BodyTrackedEntity?
let characterOffset: SIMD3<Float> = [-1.0, 0, 0]
let characterAnchor = AnchorEntity()
struct ContentView : View {
var body: some View {
return ARViewContainer().edgesIgnoringSafeArea(.all)
}
}
struct ARViewContainer: UIViewRepresentable {
func makeUIView(context: Context) -> ARView {
let arView = ARView(frame: .zero)
arView.setupARConfiguration()
arView.loadbody()
arView.scene.addAnchor(characterAnchor)
return arView
}
func updateUIView(_ uiView: ARView, context: Context) {}
}
extension ARView: ARSessionDelegate {
func setupARConfiguration() {
let configuration = ARBodyTrackingConfiguration()
self.session.run(configuration)
self.session.delegate = self
}
func loadbody(){
var cancellable: AnyCancellable? = nil
cancellable = Entity.loadBodyTrackedAsync(named: "robot.usdz").sink(
receiveCompletion: { completion in
if case let .failure(error) = completion {
print("Error: Unable to load model: \(error.localizedDescription)")
}
cancellable?.cancel()
}, receiveValue: { (character: Entity) in
if let character = character as? BodyTrackedEntity {
character.scale = [1.0, 1.0, 1.0]
cancellable?.cancel()
} else {
print("Error: Unable to load model as BodyTrackedEntity")
}
})
}
public func session(_ session: ARSession, didUpdate anchors: [ARAnchor]) {
for anchor in anchors {
guard let bodyAnchor = anchor as? ARBodyAnchor else { continue }
let bodyPosition = simd_make_float3(bodyAnchor.transform.columns.3)
characterAnchor.position = bodyPosition + characterOffset
characterAnchor.orientation = Transform(matrix: bodyAnchor.transform).rotation
if let character = character, character.parent == nil {
characterAnchor.addChild(character)
}
}
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif