Use*_*404 5 augmented-reality swift swiftui realitykit
我想从我的场景中删除一个实体。
我在 UpdateUIView 函数中创建了实体,如下所示:
// create anchor and model-Entity
let anchor = AnchorEntity(plane: .horizontal)
let cube = MeshResource.generateBox(size: 0.1, cornerRadius: 0.03)
let material = SimpleMaterial(color: .gray, roughness: 0.2, isMetallic: true)
let cubeEntity = ModelEntity(mesh: cube, materials: [material])
anchor.addChild(cubeEntity)
uiView.scene.addAnchor(anchor)
Run Code Online (Sandbox Code Playgroud)
现在我想通过按用户界面中的按钮来删除它。通过按下按钮,我将变量从 false 更改为 true。然后我在UpdateUIView函数里面写了:
if remove == true {
uiView.scene.removeAnchor(anchor)
}
Run Code Online (Sandbox Code Playgroud)
当我按下按钮时,它会将布尔值更改为 true,但实体不会消失。
关于如何解决这个问题有什么建议吗?
使用以下代码可以获得所需的结果:
import SwiftUI
import RealityKit
struct ARViewContainer: UIViewRepresentable {
@Binding var showed: Bool
let anchor = AnchorEntity(world: [0, 0,-1])
func makeUIView(context: Context) -> ARView {
let arView = ARView(frame: .zero)
let cube = MeshResource.generateBox(size: 0.8, cornerRadius: 0.02)
let material = SimpleMaterial(color: .red, isMetallic: true)
let cubeEntity = ModelEntity(mesh: cube, materials: [material])
anchor.addChild(cubeEntity)
arView.scene.addAnchor(anchor)
return arView
}
func updateUIView(_ uiView: ARView, context: Context) {
if showed == true {
uiView.scene.removeAnchor(anchor)
}
}
}
Run Code Online (Sandbox Code Playgroud)
struct ContentView : View {
@State private var show = false
var body: some View {
VStack {
ARViewContainer(showed: $show)
VStack {
Button(action: { self.show.toggle() }) {
Text("Remove Model")
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
不必在updateUIView(...)实例方法中更新内容。相反,您可以使用具有自定义方法的CoordinatormakeCoordinator()类。
| 归档时间: |
|
| 查看次数: |
2832 次 |
| 最近记录: |