3

我正在用 Swift 中的 RealityKit 加载 USDZ 模型。该模型的纹理加载良好。

但是,我无法更改材质的漫反射属性,材质总是以AnyMaterial.

我可以用 a 完全覆盖材质,SimpleMaterial或者我可以在运行应用程序之前更改 USDZ 漫反射颜色,但在运行时似乎无法这样做,有什么想法吗?

我只想能够改变一个属性

/*
Find an entity within the parent, and find the material, test to try and change it's material
**/
private func updateColor(entity: Entity) {

    guard
        let found = entity.findEntity(named: "MyItem"),
        var modelComponent = found.components[ModelComponent] as? ModelComponent,
        let existingMaterial = modelComponent.materials.first else {
        return
    }

    // This is `AnyMaterial` - no diffuse property
    // What can I use here to change the diffuse?
    modelComponent.materials = [existingMaterial]

    // Change to yellow for testing
    //var material = SimpleMaterial()
    //material.baseColor = .color(.yellow)
    //modelComponent.materials = [material]

    found.components.set(modelComponent)
}
4

1 回答 1

7

在 RealityKit 1.0 中,您可以在运行时更改材质,但不能为其参数设置动画。

这是一个代码:

class ViewController: UIViewController {
    
    @IBOutlet var arView: ARView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let modelAnchor = try! Experience.loadBox()

        modelAnchor.steelBox!.scale = [10,10,10]
        let entity: Entity = modelAnchor.steelBox!.children[0]
        arView.scene.anchors.append(modelAnchor)
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.5) {

            var material = SimpleMaterial()
            material.baseColor = try! .texture(.load(named: "texture.jpg"))
            
            var component: ModelComponent = entity.components[ModelComponent]!.self   
            component.materials = [material]
            entity.components.set(component)
        }
    }
}


在 iOS 15 的 RealityKit 2.0 中,您可以稍微不同地设置材质的颜色和纹理:

var material = SimpleMaterial()

material.color =  .init(tint: .green, texture: nil)
于 2020-06-14T17:00:08.880 回答