RealityKit检测到图像锚点时如何播放Reality Composer内置动画
解决方案
完整修改后代码
import Combine import RealityKit import ARKit struct ARViewContainer: UIViewRepresentable { func makeCoordinator() -> Coordinator { Coordinator() } func makeUIView(context: Context) -> ARView { let arView = CustomARView(frame: .zero) // 生成图像锚点 let anchor = AnchorEntity(.image(group: "AR Resources", name: "imageAnchor")) // 从Reality Composer工程加载3D模型 let box = try! Experience.loadBox() anchor.addChild(box) arView.scene.addAnchor(anchor) // 监听图像锚点识别状态 anchor.$isAnchored .receive(on: DispatchQueue.main) .sink { isAnchored in // 仅在锚点被成功识别时执行逻辑 guard isAnchored else { return } // 方式1:触发Reality Composer中设置的动画通知 // 需和你在Reality Composer中设置的通知名称一致,默认与动画类型同名 box.notifications.easeOut.post() // 方式2:直接播放模型自带的所有动画资源,无需提前配置通知 // box.availableAnimations.forEach { animation in // box.playAnimation(animation, transitionDuration: 0.3) // } } .store(in: &context.coordinator.cancellables) return arView } func updateUIView(_ uiView: ARView, context: Context) {} // 用于存储监听对象的生命周期管理类 class Coordinator { var cancellables = Set<AnyCancellable>() } }
核心修改说明
- 新增
Coordinator内部类存储Combine框架的监听实例,避免监听被系统提前回收导致回调不生效 - 监听锚点实体的
isAnchored属性,当属性变为true时即代表ARSession已经成功识别到目标图像锚点 - 识别成功后两种方式触发动画:
- 如果你在Reality Composer中为"Ease Out"动画配置了通知触发器,直接调用对应通知的
post()方法即可触发,通知名默认和你选择的动画类型一致,可自行在Reality Composer中修改 - 如果没有配置通知,直接遍历模型的
availableAnimations属性,调用playAnimation方法即可播放所有自带动画
- 如果你在Reality Composer中为"Ease Out"动画配置了通知触发器,直接调用对应通知的
- 如需循环播放动画,可调用
animation.repeat(duration: .infinity)生成循环动画实例再播放
内容的提问来源于stack exchange,提问作者lukanikolich
相关产品推荐
相关产品推荐

