0

AnimationPlaybackController has only resume(), pause() and stop() methods in RealityKit.

func move(to:relativeTo:duration:timingFunction:)

How to loop or repeat asset's animation?

Andy Jazz
  • 49,178
  • 17
  • 136
  • 220
zhou junhua
  • 462
  • 1
  • 4
  • 12

1 Answers1

0

You can infinitely loop or repeat a certain number of times an asset's animation in RealityKit using playAnimation(_:transitionDuration:startsPaused:) instance method (but I see no loop options when you use methods like move(to:relativeTo:duration:timingFunction:)):

@discardableResult 
func playAnimation(_ animation: AnimationResource, 
            transitionDuration: TimeInterval = 0, 
                  startsPaused: Bool = false) -> AnimationPlaybackController

Here's how an infinite animation loop may look like in real code:

let model = try ModelEntity.load(named: "guitarist")

let anchor = AnchorEntity(world: [2, 0, 3])
anchor.children.append(model)
arView.scene.anchors.append(anchor)
        
model.playAnimation(model.availableAnimations[0].repeat(),
                    transitionDuration: 0.5, 
                          startsPaused: false)

Also you can use a loop a definite number of times (for instance, 9).

model.playAnimation(model.availableAnimations[0].repeat(count: 9),
                    transitionDuration: 1.0, 
                          startsPaused: true)

Or using Int.max value you can address 9.2 Quintillion times to repeat an animation:

model.playAnimation(model.availableAnimations[0].repeat(count: .max),
                    transitionDuration: 1.0, 
                          startsPaused: true)

Mentioned move(to:relativeTo:duration:timingFunction:) method could be used like this:

model.move(to: .init(1.0), relativeTo: nil, 
                             duration: 10, 
                       timingFunction: .default).resume()  // No loop options

Alternative method

As a workaround, you can use physics to implement an eternal loop rotation:

model.components[PhysicsBodyComponent.self] = .init()
model.components[PhysicsMotionComponent.self] = .init()
model.physicsBody?.massProperties.mass = 0.0
model.physicsMotion?.angularVelocity.y = 1.0
model.generateCollisionShapes(recursive: true)
Andy Jazz
  • 49,178
  • 17
  • 136
  • 220