有没有办法以编程方式更改在 Reality Composer 中创建的实体的材质?

bec*_*ckp 3 augmented-reality swift arkit realitykit reality-composer

我想在 Reality Composer 中创建实体后以编程方式更改实体的颜色。

由于 Reality Composer 不会创建 ModelEntity(它创建通用实体),因此我似乎无权更改其颜色。当我类型转换为 ModelEntity 时,我现在可以访问 ModelComponent 材质。但是,当我尝试将其添加到场景中时,出现 Thread 1: signal SIGABART 错误。无法将“RealityKit.Entity”(0x1fcebe6e8)类型的值转换为“RealityKit.ModelEntity”(0x1fceba970)。下面的示例代码。

import UIKit
import RealityKit

class ViewController: UIViewController {

    @IBOutlet var arView: ARView!

    override func viewDidLoad() {
        super.viewDidLoad()
    
        // Load the "Box" scene from the "Experience" Reality File
        let boxAnchor = try! Experience.loadBox()
    
        // Typecast Steelbox as ModelEntity to change its color
        let boxModelEntity = boxAnchor.steelBox as! ModelEntity
    
        // Remove materials and create new material
        boxModelEntity.model?.materials.removeAll()
    
        let blueMaterial = SimpleMaterial(color: .blue, isMetallic: false)
        boxModelEntity.model?.materials.append(blueMaterial)
    
        // Add the box anchor to the scene
        arView.scene.anchors.append(boxAnchor)
    }
}
Run Code Online (Sandbox Code Playgroud)

ARG*_*Geo 5

模型实体存储在 RealityKit 的层次结构中更深的位置,正如您所说,它是Entity,而不是ModelEntity。因此,使用向下转型来访问meshand materials

import UIKit
import RealityKit

class ViewController: UIViewController {
    
    @IBOutlet var arView: ARView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let boxScene = try! Experience.loadBox()
        print(boxScene)
        
        let modelEntity = boxScene.steelBox?.children[0] as! ModelEntity
        let material = SimpleMaterial(color: .green, isMetallic: false)
        modelEntity.model?.materials = [material]
        
        let anchor = AnchorEntity()
        anchor.scale = [5,5,5]
        modelEntity.setParent(anchor)
        arView.scene.anchors.append(anchor)
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,这篇文章这篇文章可能会有所帮助。

  • 我将子下标添加到上面发布的代码中,并且它使用现有的 Reality Composer 锚点进行工作。我为此奋斗了几个小时,谢谢!我需要阅读更多有关儿童的内容。现场的打印命令也是一个很好的提示。 (2认同)
  • 很高兴))对于盒子场景,您还可以使用下标 `boxScene.children[0].children[0].children[0].children[0]` 而不是 `boxScene.steelBox?.children[0]`。 (2认同)