RealityKit,通过State或ObservedObject更改更改纹理或材质

时间:2020-05-07 09:47:35

标签: swiftui arkit realitykit

我正在尝试通过按下按钮来更改纹理。 加载usdz(createData())或创建文本效果很好,添加材质和纹理...

但是当更改状态或ContentView中绑定的ObservedObject时,纹理不会更新...

能否请别人给我一个提示,在哪里或如何更新我的模型?

struct ContentView : View {
@ObservedObject var store = TextureStore()

func setMyCurrentTexture(textureName: String){
    store.myCurrentTexture = textureName
}

var body: some View {
    VStack {
        ARViewContainer(texture: $store.myCurrentTexture).edgesIgnoringSafeArea(.all)
        Spacer()
        HStack {
            Button(action: {
                self.setMyCurrentTexture(textureName: "one")
            }) {Text("Use texture one")}
            Spacer()
            Button(action: {self.setMyCurrentTexture(textureName: "two")
            }) {Text("Use texture two")}
        }
    }
}

}

struct ARViewContainer: UIViewRepresentable {
@Binding var texture: String

func makeUIView(context: Context) -> ARView {

    let arView = ARView(frame: .zero)
    let myurl  = URL(fileURLWithPath: "cube", relativeTo: FileManager.documentDirectoryURL).appendingPathExtension("usdz")
    let redbox = try? Entity.load(contentsOf: myurl)

    let textShape = MeshResource.generateText("nice text shape")
    var textMaterial = SimpleMaterial()

    do {
        try textMaterial.baseColor = .texture(.load(named: texture))
    } catch  {
        textMaterial.tintColor = UIColor(cgColor: #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1))
    }

    let myText = ModelEntity(mesh: textShape, materials: [textMaterial])

    redbox?.scale = [0.3, 0.3, 0.3]
    myText.orientation = simd_quatf(angle: 3*Float.pi/2, axis: [1, 0, 0])
    myText.scale = [0.1, 0.1, 0.1]


    //         Creating parent ModelEntity
    let parentEntity = ModelEntity()
    parentEntity.addChild(redbox!)
    parentEntity.addChild(myText)

    let entityBounds = redbox!.visualBounds(relativeTo: parentEntity)
    parentEntity.collision = CollisionComponent(shapes: [ShapeResource.generateBox(size: entityBounds.extents).offsetBy(translation: entityBounds.center)])

    let anchor = AnchorEntity(plane: .any , classification: .any )
    anchor.addChild(parentEntity)

    arView.scene.anchors.append(anchor)
    arView.installGestures(.all, for: parentEntity)

    return arView

}

func updateUIView(_ uiView: ARView, context: Context) {
    // I COULD PRINT INTO CONSOLE, THAT texture IS CHANGING

    var material = SimpleMaterial()
    do {
        try material.baseColor = .texture(.load(named: texture))
    } catch  {
        material.tintColor = UIColor(cgColor: #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1))
    }

    // BUT HOW TO ATTACH TO MY CUBE OR TO MY TEXT
    // I CAN TRIGGER THE VISIBILITY TOUGH WITH isEnabled

}

}

0 个答案:

没有答案