在 RealityKit 中播放 USDZ 动画

Sil*_*ing 4 animation augmented-reality swift realitykit

我花了 2 天的时间试图了解如何在我的 RealityKit 项目中正确播放动画。

我遵循了其他 stackoverflow 主题的许多提示,但没有成功。我知道使用 RealityKit v2 我们只能播放 usdz 文件中的第一个动画,好吧。我正在尝试直接在 Reality Composer 中播放 Apple 提供的“toy_robot_vintage.usdz”的第一个动画。

这是我的完整代码:

func loadModel(named: String, result: ARRaycastResult) {
        
        var usdzToLoad: String = ""
        
        switch named {
        case "ROBOT":
            usdzToLoad = "toy_robot_vintage.usdz"
        default:
            break;
        }
        
        DispatchQueue.main.async {
            let modelToLoad = try! ModelEntity.loadModel(named: usdzToLoad)
            
            switch named {
            case "ROBOT":
                modelToLoad.name = "ROBOT"
            default:
                break;
            }
            
            let anchor = AnchorEntity(plane: .horizontal, classification: .any, minimumBounds: [0.1, 0.1])
                anchor.position.y = 0.01
                anchor.addChild(modelToLoad)
            
            // Create a "Physics" model of the toy in order to add physics mode
            guard let modelEntity = anchor.children.first as? (Entity & HasPhysics)
            else { return }

            self.arView.installGestures([.rotation], for: modelEntity)
            
            modelEntity.generateCollisionShapes(recursive: true)
            modelEntity.physicsBody = PhysicsBodyComponent(shapes: [.generateBox(size: .one)],
                                                           mass: 1.0,
                                                           material: .default,
                                                           mode: .kinematic)

            self.currentEntity = modelEntity
            self.anchorsEntities.append(anchor)
            
            self.arView.scene.addAnchor(anchor)
            
//            self.currentEntity!.availableAnimations.forEach { self.currentEntity!.playAnimation($0.repeat()) }
            
            let robotAnimationResource = self.currentEntity?.availableAnimations.first
            
            self.currentEntity!.playAnimation(robotAnimationResource!.repeat(duration: .infinity),
                                             transitionDuration: 1.25,
                                                   startsPaused: false)
        }
Run Code Online (Sandbox Code Playgroud)

当我尝试播放动画时,robotAnimationResource 始终为零,当然返回致命错误。

任何想法 ?预先感谢您的帮助和支持。

max*_*zer 6

更改ModelEntity.loadModelModelEntity.load,现在应该有动画了。
这很奇怪,我不知道为什么,但这过去对我有用。

此外 HasPhysics 继承了 Entity,因此为了节省自己寻找锚点的子级等,您应该能够guard let modelEntity...用以下内容替换该行:

guard let modelEntity = modelToLoad as? HasPhysics else { return }
Run Code Online (Sandbox Code Playgroud)

编辑:

我刚刚在操场上运行了这个,动画运行良好:

guard let modelEntity = modelToLoad as? HasPhysics else { return }
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

问题是,以这种方式导入的模型不符合 HasPhysics(如果您提到这就是它现在对您来说失败的地方,那么很有用)。

将 ModelComponent 应用于另一个实体类或 ModelEntity。