如果您想尝试使用USDZ文件链接是
Here(仍然可以使用任何其他动画USDZ文件进行测试):Https://www.worldhotelity.com/stack/run.usdz, 我得益于Apple Developers论坛的一些帮助,发现了解决方案,可以从
AnimationDefinition
方法转换为AnimationPlaybackController
由于需要将控制器声明为全局变量
在使用它播放动画之后
guard let animationResource = manPlayer.availableAnimations.first else { return }
playbackController = manPlayer.playAnimation(animationResource.repeat(duration: .infinity), transitionDuration: 0.25, startsPaused: false) //infinity looping, smooth transition, animation starts immediately
playbackController?.speed = speed
然后您可以使用它来控制速度以后
speed += 0.1
playbackController?.speed = speed
这里是以下完整代码:
import SwiftUI
import RealityKit
struct ContentView: View {
@State var manPlayer = Entity()
@State var speed:Float = 0.5
@State private var playbackController: AnimationPlaybackController?
var body: some View {
VStack {
RealityView { content in
if let item = try? await Entity(named: "run.usdz") {
manPlayer = item
content.add(manPlayer)
}
}
HStack {
Button(action: playThis) {
Text("Play")
}
Button(action: increaseSpeed) {
Text("increase Speed (+) ")
}
Button(action: decreaseSpeed) {
Text("decrease Speed (-) ")
}
}
}
}
func playThis() {
guard let animationResource = manPlayer.availableAnimations.first else { return }
playbackController = manPlayer.playAnimation(animationResource.repeat(duration: .infinity), transitionDuration: 0.25, startsPaused: false) //infinity looping, smooth transition, animation starts immediately
playbackController?.speed = speed
}
func increaseSpeed() {
speed += 0.1
playbackController?.speed = speed
}
func decreaseSpeed() {
speed -= 0.1
playbackController?.speed = speed
}
}