VisionPro开发 - 设置模型阴影

226 阅读1分钟

昨天收到公众号私信,有个问题想咨询我如何解决,大致的意思是通过一下代码设置模型的阴影,但是不起作用。

bagEntity.components.set(GroundingShadowComponent(castsShadow: true))

我实验了一下,确实不起作用,如下图所示:

通过万能的Google搜索找到解决办法:

bagEntity.enumerateHierarchy { entity, stop in
    if entity is ModelEntity {
        entity.components.set(GroundingShadowComponent(castsShadow: true))
    }
}

除了以上代码,还需要 声明一个Entity的扩展

extension Entity {
    
    /// Executes a closure for each of the entity's child and descendant
    /// entities, as well as for the entity itself.
    ///
    /// Set `stop` to true in the closure to abort further processing of the child entity subtree.
    func enumerateHierarchy(_ body: (Entity, UnsafeMutablePointer<Bool>) -> Void) {
        var stop = false

        func enumerate(_ body: (Entity, UnsafeMutablePointer<Bool>) -> Void) {
            guard !stop else {
                return
            }

            body(self, &stop)
            
            for child in children {
                guard !stop else {
                    break
                }
                child.enumerateHierarchy(body)
            }
        }
        
        enumerate(body)
    }
    
}

这样就可以遍历usdz中的所有Entity,并设置阴影了,阴影效果如下。

前后对比视频:

请移步公众号GunnerTalk

希望可以帮助到有需要的人,大家如果遇到其他问题也欢迎给我留言