Search code examples
animationaugmented-realityrealitykitios-animations

RealityKit: change the scale of a ModelEntity without changing its position


I have an ModelEntity animation that move from point A to point B and takes a while to complete. When the user taps on the ModelEntity I would like to add a shrinking animation to the ModelEntity as well.

I tried adding the scale animation directly to the ModelEntity view .move but the problem there is I current transform of the model is where the model is expected to end. Causing the ModelEnity to jump to the end of the animation.

var transform = modelEntity.transform 
transform.scale *= factor
modelEntity.move(to: transform, relativeTo: modelEntity.parent, duration: duration) // will not work because the translation of the transform is already at the end of the animation

Is there a way to add a scaling animation to ModelEntity that is already in the middle of a different animation and make them work together?


Solution

  • Tested with Xcode 14.2. :

    import RealityKit
    import CoreGraphics
    
    extension Entity {
        
        func scaleAnimated(with value: SIMD3<Float>, duration: CGFloat) {
            
            var scaleTransform: Transform = Transform()
            scaleTransform.scale = value
            self.move(to: self.transform, relativeTo: self.parent)
            self.move(to: scaleTransform, relativeTo: self.parent, duration: duration)
            
        }
        
    }
    

    Usage:

    var scaleTransform: Transform = Transform()
            
    if exampleEntity.scale.x == 1.0 {
       exampleEntity.scaleAnimated(with: [0.012, 0.012, 0.012], duration: 1.0)
    } else {
        exampleEntity.scaleAnimated(with: [1.0, 1.0, 1.0], duration: 1.0)
    }