我们在Day 8中演示了attachment的实现,本节的知识点是portal。portal相当于哆啦A梦里的任意门,它让我们可以打开另一个世界,这个世界独立于当前的世界,具有单独的光照系统并且由portal几何图形进行遮罩。
要创建portal,首先就需要创建一个世界(makeWorld
),在其中可以添加自己的实体。接着创建portal并将其关联至刚刚创建的世界。
主要的代码如下:
import SwiftUI
import RealityKitstruct ContentView: View {var body: some View {RealityView { content inlet world = makeWorld()let portal = makePortal(world: world)content.add(world)content.add(portal)}}func makeWorld() -> Entity {let world = Entity()world.components[WorldComponent.self] = .init()let environment = try! EnvironmentResource.load(named: "Sunlight")world.components[ImageBasedLightComponent.self] = .init(source: .single(environment), intensityExponent: 12)world.components[ImageBasedLightReceiverComponent.self] = .init(imageBasedLight: world)let earth = try! ModelEntity.load(named: "Earth")earth.position = SIMD3<Float>(x: -0.1, y: 0, z: -0.4)world.addChild(earth)return world}func makePortal(world: Entity) -> Entity {let portal = Entity()portal.components[ModelComponent.self] = .init(mesh: .generatePlane(width: 0.5, height: 0.5, cornerRadius: 0.5), materials: [PortalMaterial()])portal.components[PortalComponent.self] = .init(target: world)return portal}}
其中的Sunlight.skybox
文件及Earth.usdz
文件请见我们的代码仓库。
示例代码:GitHub仓库
其它相关内容请见虚拟现实(VR)/增强现实(AR)&visionOS开发学习笔记