问题
In my previous question I already found how to put a rotation transform over only one axis on an object, now I want this to be animated.
Is there a way to do this in RealityKit?
回答1:
Here's how you can animate object in
RealityKit
(for simplicity I made it using macOS app):
import RealityKit
class ViewController: NSViewController {
@IBOutlet var arView: ARView!
let boxAnchor = try! Experience.loadBox()
override func awakeFromNib() {
boxAnchor.steelBox?.scale = [10, 10, 10]
let rotation = Transform(pitch: 0, yaw: 0, roll: .pi)
boxAnchor.steelBox?.orientation = rotation.rotation
arView.scene.anchors.append(boxAnchor)
boxAnchor.steelBox?.move(to: rotation,
relativeTo: boxAnchor.steelBox,
duration: 5.0,
timingFunction: .linear)
}
}
Or you can use an
animationPlaybackController
to play a ready animation made in 3D app:
import RealityKit
class ViewController: NSViewController {
@IBOutlet var arView: ARView!
override func awakeFromNib() {
do {
let robot = try ModelEntity.load(named: "drummer")
let anchor = AnchorEntity(world: [0, -0.7, 0])
anchor.transform.rotation = simd_quatf(angle: .pi/4,
axis: [0, 1, 0])
arView.scene.anchors.append(anchor)
robot.scale = [1, 1, 1] * 0.1
anchor.children.append(robot)
robot.playAnimation(robot.availableAnimations[0].repeat(),
transitionDuration: 0.5,
startsPaused: false)
} catch {
fatalError("Cannot load USDZ asset.")
}
}
}
回答2:
Rotation with animation:
copy the box's current transform
var rotationTransform = boxAnchor.steelBox?.transform
set the box to rotate 90 degrees over z-axis
rotationTransform?.rotation = simd_quatf(angle: .pi/2, axis: [0,0,1])
move the box to the new transform over 10s
boxAnchor.steelBox?.move(to: rotationTransform!, relativeTo: boxAnchor.steelBox?.parent, duration: 10, timingFunction: .easeInOut)
Translation with animation:
var translationTransform = boxAnchor.steelBox?.transform
translationTransform?.translation = SIMD3<Float>(x: 5, y: 0, z: 0)
boxAnchor.steelBox?.move(to: translationTransform!, relativeTo: boxAnchor.steelBox?.parent, duration: 10, timingFunction: .easeInOut)
Scale with animation:
var scaleTransform = boxAnchor.steelBox?.transform
scaleTransform?.scale = SIMD3<Float>(x: 1, y: 1, z: 1)
boxAnchor.steelBox?.move(to: scaleTransform!, relativeTo: boxAnchor.steelBox?.parent, duration: 10, timingFunction: .easeInOut)
来源:https://stackoverflow.com/questions/59335075/how-to-animate-a-transform-in-realitykit