swift 我可以在RealityKit中控制Reality Composer的行为吗?

6rqinv9w  于 2023-02-03  发布在  Swift
关注(0)|答案(1)|浏览(127)

我想用SwiftUI做一个按钮,按钮按下后,模型会隐藏,我已经看过这个链接(Creating a Trigger)的教程,但是不知道如何编程控制。
下面是我的代码:

struct VocabView : View {
    
    @State private var arView = ARView(frame: .zero)

    var body: some View {
        ZStack{
            ARViewContainer(arView: $arView)
                .ignoresSafeArea()
            VStack {
                Button("hide") {
                    hide()
                }    
            }
        }
    }
    
    func hide() {
        let demoScene = try! Experience1.loadDemo()
        if arView.scene.anchors.count > 0 {
            if arView.scene.anchors[0].isAnchored {
                demoScene.notifications.hide.post()
            }
        }
    }
}

struct ARViewContainer2: UIViewRepresentable {
    
    @Binding var arView: ARView
    
    func makeUIView(context: Context) -> ARView {
        
        let demoScene = try! Experience1.loadDemo()

        DispatchQueue.main.async {
            arView.scene.anchors.append(demoScene)
        }
        
        return arView
        
    } 
}

以下是Reality Composer中的配置:

ukdjmx9f

ukdjmx9f1#

您正在加载您的模型两次-第一次在makeUIView()方法中,第二次在hide()方法中。

import SwiftUI
import RealityKit

struct ContentView : View {

    @State private var arView = ARView(frame: .zero)
    @State private var scene = try! Experience.loadBox()

    var body: some View {
        ZStack{
            ARViewContainer(arView: $arView, scene: $scene)
                .ignoresSafeArea()
            VStack {
                Spacer()
                Button("Hide Model") { hideModel() }
            }
        }
    }
    private func hideModel() {
        if arView.scene.anchors.count > 0 {
            if arView.scene.anchors[0].isAnchored {
                scene.notifications.notify.post()
            }
        }
    }
}

struct ARViewContainer : UIViewRepresentable {

    @Binding var arView: ARView
    @Binding var scene: Experience.Box
    
    func makeUIView(context: Context) -> ARView {
        arView.scene.anchors.append(scene)
        return arView
    }
    func updateUIView(_ view: ARView, context: Context) { }
}

相关问题