在 SceneKit 中按名称获取材质

Posted

技术标签:

【中文标题】在 SceneKit 中按名称获取材质【英文标题】:Get material by name in SceneKit 【发布时间】:2016-12-14 04:42:44 【问题描述】:

我已将一个 collada .dae 文件导入到 scenekit 中。 我可以在场景编辑器/检查器中看到具有命名材质的实体和材质列表。但我不知道如何以编程方式要求这些。

如果我知道一个节点和使用它的几何体,我可以按名称从几何体对象中请求材质,如下所示:

myscene.rootNode.childNodes[68].geometry?.materialWithName("carpaint")

但是这些是用于许多子几何形状的可重复使用的材料,所以在某处应该有一个全局索引(?)

我会期待类似的东西

myscene.materialWithName("carpaint")

【问题讨论】:

我常用的一种方法是在场景中的某处添加一个不显眼的对象,该对象使用所有材质,并从那里参考材质。至少它比遍历场景中的所有节点寻找材质要快。 【参考方案1】:

我最终做的是为 SCNNode 和 SCNScene 创建一个扩展,为我提供所有材料的索引:

import SceneKit

extension SCNScene 
    func buildMaterialIndex() -> Dictionary<String, SCNMaterial> 
        return self.rootNode.buildMaterialIndex()
    


extension SCNNode 
    func isPartOf(node: SCNNode) -> Bool 
        return (node === self) || (parentNode?.isPartOf(node) ?? false)
    

    private class _DictBox 
        var dict = Dictionary<String, SCNMaterial>()
    
    private func _populateMaterialIndex(dictbox: _DictBox, node: SCNNode) 
        if let g = node.geometry 
            for m in g.materials 
                if let n = m.name 
                    dictbox.dict[n] = m
                
            
        
        for n in node.childNodes 
            _populateMaterialIndex(dictbox, node: n)
        
    
    func buildMaterialIndex() -> Dictionary<String, SCNMaterial> 
        let dictbox = _DictBox()
        _populateMaterialIndex(dictbox, node: self)
        return dictbox.dict
    

【讨论】:

以上是关于在 SceneKit 中按名称获取材质的主要内容,如果未能解决你的问题,请参考以下文章