如何在RealityKit中为程序化创建的实体添加阴影?
问题描述
我通过代码创建了一系列Box实体,在与桌面接触的位置存在轻微的环境光遮蔽,但未显示任何阴影——既没有地面阴影,也没有实体自身投射的阴影。不过使用Reality Composer创建的模型可以正常显示地面阴影。

系统环境:iOS 16.1.1
问题代码
let config = ARWorldTrackingConfiguration() config.planeDetection = [.horizontal] session.run(config, options: []) let anchorEntity = AnchorEntity(plane: .horizontal) scene.addAnchor(anchorEntity) var material = PhysicallyBasedMaterial() material.baseColor = PhysicallyBasedMaterial.BaseColor(tint: .white) let box1 = ModelEntity(mesh: .generateBox(size: [0.05, 0.03, 0.05]), materials: [material]) box1.position = [0, 0.015, 0] anchorEntity.addChild(box1) let box2 = ModelEntity(mesh: .generateBox(size: [0.15, 0.03, 0.05]), materials: [material]) box2.position = [0.05, 0.045, 0] anchorEntity.addChild(box2) let box3 = ModelEntity(mesh: .generateBox(size: [0.01, 0.05, 0.01]), materials: [material]) box3.position = [0, 0.085, 0] anchorEntity.addChild(box3)
解决方法
RealityKit中代码生成的模型默认不会启用阴影投射与接收,而Reality Composer创建的模型会自动配置这些属性。你需要手动为每个ModelEntity设置以下属性:
- 启用阴影投射:设置
castsShadow = true - 启用阴影接收:设置
receivesShadow = true
场景默认的环境光组件已支持阴影渲染,无需额外配置。
修改后的代码示例
let config = ARWorldTrackingConfiguration() config.planeDetection = [.horizontal] session.run(config, options: []) let anchorEntity = AnchorEntity(plane: .horizontal) scene.addAnchor(anchorEntity) var material = PhysicallyBasedMaterial() material.baseColor = PhysicallyBasedMaterial.BaseColor(tint: .white) // 配置第一个Box let box1 = ModelEntity(mesh: .generateBox(size: [0.05, 0.03, 0.05]), materials: [material]) box1.position = [0, 0.015, 0] box1.castsShadow = true box1.receivesShadow = true anchorEntity.addChild(box1) // 配置第二个Box let box2 = ModelEntity(mesh: .generateBox(size: [0.15, 0.03, 0.05]), materials: [material]) box2.position = [0.05, 0.045, 0] box2.castsShadow = true box2.receivesShadow = true anchorEntity.addChild(box2) // 配置第三个Box let box3 = ModelEntity(mesh: .generateBox(size: [0.01, 0.05, 0.01]), materials: [material]) box3.position = [0, 0.085, 0] box3.castsShadow = true box3.receivesShadow = true anchorEntity.addChild(box3)
便捷封装(可选)
如果需要批量创建带阴影的Box,可以封装工具方法:
func createShadowEnabledBox(size: SIMD3<Float>, material: PhysicallyBasedMaterial) -> ModelEntity { let box = ModelEntity(mesh: .generateBox(size: size), materials: [material]) box.castsShadow = true box.receivesShadow = true return box }
调用示例:
let box1 = createShadowEnabledBox(size: [0.05, 0.03, 0.05], material: material) box1.position = [0, 0.015, 0] anchorEntity.addChild(box1)
内容的提问来源于stack exchange,提问作者Mark Horgan
相关产品推荐
相关产品推荐

