visionOS空间计算实战开发教程Day 9 打造“任意门”

我们在​​Day 8​​中演示了attachment的实现,本节的知识点是portal。portal相当于哆啦A梦里的任意门,它让我们可以打开另一个世界,这个世界独立于当前的世界,具有单独的光照系统并且由portal几何图形进行遮罩。

要创建portal,首先就需要创建一个世界(​​makeWorld​​),在其中可以添加自己的实体。接着创建portal并将其关联至刚刚创建的世界。

主要的代码如下:

复制代码
import SwiftUI
import RealityKit

struct ContentView: View {
    var body: some View {
        RealityView { content in
            let 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开发学习笔记​

相关推荐
东坡肘子1 天前
春晚、机器人、AI 与 LLM -- 肘子的 Swift 周报 #124
人工智能·swiftui·swift
君赏2 天前
第三十二章 接下来我们开始做`灭菌整板`页面
swiftui
君赏2 天前
第三十章 接下来我们写首页的功能,首先是我们的`托盘绑定箱号`。
swiftui
君赏2 天前
第三十一章 完善箱号列表
swiftui
君赏2 天前
第二十五章 完善登录逻辑
swiftui
君赏2 天前
第二十六章 Focused
swiftui
君赏2 天前
第 二十章 @Published sink
swiftui
君赏2 天前
第二十一章 @ViewBuilder默认实现|Toggle|我的页面封装
swiftui
君赏2 天前
第二十九章 修复首页 PopMenuView 显示问题
swiftui
君赏2 天前
第二十八章 重置 ObservableObject 模型数据
swiftui