Hi everyone,
I need to synchronize the playback of RealityKit Timelines via SharePlay.
To do this I am trying to get the references of the timelines using "AnimationPlaybackController" and "AnimationResource". In my realitykit scene I have configured both an animation (with blender), and a timeline, the animation starts correctly when the realitykit scene starts, the timeline not.
Below the code:
struct ContentView: View {
@State private var subscriptions = [EventSubscription]()
@Environment(AppModel.self)
private var appModel
let rootEntity = Entity()
@State var testEntity: Entity?
@State var testAnimation: AnimationResource?
@State var testController: AnimationPlaybackController?
init() {
CubeComponent.registerComponent()
}
var body: some View {
RealityView { content in
content.add(rootEntity)
if let scene = try? await Entity(named: "Room", in: realityKitContentBundle) {
rootEntity.addChild(scene)
playAnimations(from: content)
}
}
.gesture(SpatialTapGesture().targetedToAnyEntity()
.onEnded({ value in
_ = value.entity.applyTapForBehaviors()
if let testEntity, let testAnimation {
testController = testEntity.playAnimation(testAnimation.repeat())
}
})
)
}
func playAnimations(from content: RealityViewContent) {
subscriptions.append(content.subscribe(to: ComponentEvents.DidAdd.self, componentType: AnimationLibraryComponent.self, { event in
let entity = event.entity
entity.components[AnimationLibraryComponent.self]?.animations.forEach({ (key, value) in
if value.definition is AnimationGroup {
if key == "/Room/TestTimeline" {
let controller = entity.playAnimation(value.repeat())
testEntity = entity
testAnimation = value
appModel.syncronizedAnimations[key] = .init(name: key, animationController: controller, entityName: entity.name)
}
} else {
if entity.name == "SphereInteractable" {
let controller = entity.playAnimation(value.repeat())
appModel.syncronizedAnimations[key] = .init(name: key, animationController: controller, entityName: entity.name)
}
}
})
}))
}
}
the variables testEntity, testAnimation and testController are for testing purposes only. If I try to start the animations in the playAnimations function, only the animation created via blender starts (the one related to the object "SphereInteractable"), the Timeline starts only if I save a reference and I play it with a tap gesture or with a delay of ! seconds with DispatchQueue.asyncAfter called in the onAppear.
is there a better way to handle this? The goal is to have a reference of the AnimationPlaybackController of the timeline, in order to sync the animation via shareplay.
Thanks