gpt4 book ai didi

swift - 在 RealityKit 中播放 USDZ 动画

转载 作者:行者123 更新时间:2023-12-05 04:55:05 28 4
gpt4 key购买 nike

我花了 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)
}

robotAnimationResource is always nil returning of course a fatal error when I try to play the animation.

有什么想法吗?在此先感谢您的帮助和支持。

最佳答案

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

HasPhysics 也继承了 Entity,所以为了避免自己寻找 anchor 的 child 等,您应该能够替换 guard let modelEntity... 行:

guard let modelEntity = modelToLoad as? HasPhysics else { return }

编辑:

我刚刚在 playground 上运行了这个并且动画运行良好:

import PlaygroundSupport
import UIKit
import RealityKit

let arview = ARView(frame: .zero, cameraMode: .nonAR, automaticallyConfigureSession: true)
arview.environment.lighting.intensityExponent = 3
let newAnchor = AnchorEntity(world: .zero)
let newEnt = try! Entity.load(named: "toy_robot_vintage")
newAnchor.addChild(newEnt)
arview.scene.addAnchor(newAnchor)
for anim in newEnt.availableAnimations {
newEnt.playAnimation(anim.repeat(duration: .infinity), transitionDuration: 1.25, startsPaused: false)
}

PlaygroundSupport.PlaygroundPage.current.liveView = arview

enter image description here

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

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

关于swift - 在 RealityKit 中播放 USDZ 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65591637/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com