Home > Software engineering >  RealityKit – Playing animation from USDZ file in Xcode 13
RealityKit – Playing animation from USDZ file in Xcode 13

Time:05-18

I'm trying to play animations from a usdz file. So I was given a .dae file and a .scn file both of the same thing. for RealityKit they only accept .usdz files. So I used Xcode's exporter and exported them both to .usdz format. However the animations do not transfer over. I also tried copying the scene graph of the .scn file and pasting it in the .usdz file and when I press the play button in the Bottom center of the viewer in Xcode. I can see the animation play.

However this is wrong because .usdz files can't be edited. so it doesn't save. and hence it doesn't play in the ARview when I run on Xcode. Here's my code for playing the animations. I have tried looking at a bunch of post from both stack overflow and apple developer forum.

bird = try! Entity.load(named: "plane")
bird.name = "bird"
resultAnchor.addChild(bird)
            
arView.scene.subscribe(to: SceneEvents.AnchoredStateChanged.self) { [self] (event) in
    if resultAnchor.isActive {
        for entity in resultAnchor.children {
            for animation in entity.availableAnimations {
                entity.playAnimation(animation.repeat())
            }
        }
    }
}.store(in: &birdAnimations) // Remember to store the cancellable!

I found the structure for the code in a post

Also I guess its important to note that I found a .usdz file online that had an animation. Quick look was able to play it when I rightclicked->Quicklook on the file in finder. But again when I try playing the animation on Xcode it doesn't play.

If you have any questions, need clarity or screenrecordings of what I am doing just ask.

CodePudding user response:

To play animation use DidAddEntity struct instead of AnchoredStateChanged.

import UIKit
import RealityKit
import Combine

class ViewController: UIViewController {
    
    @IBOutlet var arView: ARView!
    var subscriptions: [AnyCancellable] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let model = try! Entity.load(named: "drummer.usdz")
        let anchor = AnchorEntity()
        anchor.addChild(model)
        arView.scene.anchors.append(anchor)
        
        arView.scene.subscribe(to: SceneEvents.DidAddEntity.self) { _ in
            if anchor.isActive {
                for entity in anchor.children {
                    for animation in entity.availableAnimations {
                        entity.playAnimation(animation.repeat())
                    }
                }
            }
        }.store(in: &subscriptions)
    }
}

CodePudding user response:

My issue wasn't with my code. It was the way I was converting the .blend/.dae file to the .usdz.

I first exported it as a .glb in blender and Maya (worked for both). Then used Apple's Reality Converter to export it as a .usdz. that was able to play the animation properly.

  • Related