swift RealityKit实体上的复杂模型组件

sauutmhj  于 2023-08-02  发布在  Swift
关注(0)|答案(1)|浏览(140)

我正在尝试使用RealityKits实体组件系统,以它的最大程度,但我有困难,组装在一起的几个部分。特别是围绕HasModel组件。
在Reality Composer中,我制作了一个由三个基本对象组成的简单模型。我将它导出为.USDZ文件,并将其放入我的Xcode项目中。


的数据
然后我从磁盘加载模型,如下所示:

guard let basicLabelFileURL = Bundle.main.url(forResource: "label", withExtension: "usdz") else {
    fatalError("Could not find label file")
}
let basicLabel = try ModelEntity.loadModel(contentsOf: basicLabelFileURL)

字符串
然后,我有一个名为LabelEntity的自定义实体

class LabelEntity: Entity, HasAnchoring, HasModel {
    
    required public init() {
        super.init()
    }
    
    public init(entity: Entity) {
        super.init()
        self.model = ??? entity?
    }
}


它会用磁盘上的模型初始化。

let newLabelEntity = LabelEntity(entity: basicLabel)


正如你所看到的,我不想使从磁盘加载的模型成为我的自定义实体的ModelComponent。然而,ModelComponent initalizer只接受单个网格,然后是材料阵列。
我的知识差距在哪里?如何使用ModelComponent从复杂的网格层次结构(其他模型)中创建自定义实体?

qlfbtfca

qlfbtfca1#

最后我只是将加载的模型作为子实体添加到“ Package 器”实体中。然而,我们在试图修改(更改材质)从磁盘加载的实体时遇到了类似的问题。以下是Entity上的一些扩展

xtension Entity {
    func explore(children: Entity.ChildCollection) {
        for (index, child) in children.enumerated() {
            print("\(index), \(child.components.self)")
            self.explore(children: child.children)
        }
    }
    
    
    func findChild<T>(entity: Entity? = nil, name: String? = nil, type: T.Type) -> T? {
        let children = findChildren(entity: entity, name: name)
        for child in children {
            if let castChild = child as? T {
                return castChild
            }
        }
        
        return nil
    }
    
    
    func findChildren(entity: Entity? = nil, name: String? = nil) -> [Entity] {
        let target = entity ?? self
        
        var foundChildren: [Entity] = []
        if (target.name == name) || (name == nil) {
            foundChildren.append(target)
        }
        
        for child in target.children {
            foundChildren = foundChildren + findChildren(entity: child, name: name)
        }
        
        return foundChildren
    }
}

字符串
未测试,但如果您获得了符合HasModel的加载模型的第一个子模型,如下所示

let myLoadedEntity: Entity = <Loaded from disk>

let firstModelEntity = myLoadedEntity.self.findChild(type: ModelEntity.self).first

let myCustomModelEntity: HasModel = <construct custom entity>

myCustomEntity.model = firstModelEntity?.model


请注意,扩展允许您按名称查找已加载实体的图层。如果你知道它,那么你可以直接用扩展名搜索它。
假设这是可行的,您可能仍然需要与资源的设计者合作,以获得正确的层。

相关问题