swift中arview配置3d物体的碰撞事件,一定要配置name

24 阅读1分钟

大家好,我的开源项目PakePlus可以将网页/Vue/React项目打包为桌面/手机应用并且小于5M只需几分钟,官网地址:pakeplus.com

给3D物体添加碰撞组件,然后在给ARView配置订阅碰撞事件,并且一定要给3D对象实体配置name属性,不然不会触发碰撞订阅事件!!!!

        // 创建红色方块在图片中心
        func imageCenterBox(anchor: ARImageAnchor, session: ARSession) {
            print("创建红色方块在图片中心")
            if let arView = arView {
                // mesh是网格
                let mesh = MeshResource.generateBox(size: 0.02)
                // matrial 是素材材质
                let material = SimpleMaterial(color: .red, roughness: 0.5, isMetallic: true)
                // 红色方块实例
                let boxEntity = ModelEntity(mesh: mesh, materials: [material])
                // 将红色方块添加到中心位置,并且在y轴向上
                boxEntity.position = [0, 0.01, 0]
                // 创建碰撞形状
                let collisionShape = ShapeResource.generateBox(size: [0.02, 0.02, 0.02])
                // 添加碰撞组件:可以用多个碰撞形状
                boxEntity.components.set(CollisionComponent(shapes: [collisionShape]))
                // 必须配置,不然不会触发碰撞事件
                boxEntity.name = "boxentity"
                // 创建锚点实例
                let anchorEntity = AnchorEntity(anchor: anchor)
                // 锚点添加模型
                anchorEntity.addChild(boxEntity)
                // 视图添加锚点
                arView.scene.addAnchor(anchorEntity)
            }
        }

配置订阅碰撞事件:

 // 收集碰撞事件的订阅,否则会不知道碰撞事件
    private var cancellables = Set<AnyCancellable>()

// 添加碰撞检测事件监听订阅消息
        self.arView?.scene.subscribe(to: CollisionEvents.Began.self) { [weak self] event in
            // 处理碰撞事件
            self?.onCollision(event)
        }.store(in: &cancellables)

cancellables是啥?

cancellables是可取消的,是框架中管理订阅生命周期的关键容器

在swift中,当你订阅一个发布者Published时,会返回一个AnyCancellable对象,这个对象需要保留,否则订阅会被理解取消。