RealityKit - Animate opacity of a ModelEntity?

后端 未结 3 1348
天命终不由人
天命终不由人 2021-01-06 12:59

By setting the color of a material on the model property of a ModelEntity, I can alter the opacity/alpha of an object. But how do you animate this?

3条回答
  •  忘掉有多难
    2021-01-06 13:51

    I tested it using different techniques and came to the sad conclusion: you can't animate a material's opacity in RealityKit framework because RealityKit materials don't support animation at runtime (for now I hope). Let's wait for RealityKit's major update.

    Here's a code you can use for test

    (arView.alpha property just works):

    import UIKit
    import RealityKit
    
    class ViewController: UIViewController {
    
        @IBOutlet var arView: ARView!
    
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
    
            arView.alpha = 1.0 
            opacityAnimation()
        }
    
        func opacityAnimation() {
    
            UIView.animate(withDuration: 5.0,
                             animations: {
    
                self.arView.alpha = 0.0
            })
        }
    }
    

    And use this code snippet in order to make sure that animation doesn't work properly

    (there's no animation process, just value assignment):

    import UIKit
    import RealityKit
    
    class ViewController: UIViewController {
    
        @IBOutlet var arView: ARView!
        let tetheringAnchor = AnchorEntity(world: [0,0,0])
        var material = SimpleMaterial()
        let mesh: MeshResource = .generateSphere(radius: 0.5)
        var sphereComponent: ModelComponent? = nil
    
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
    
            material.metallic = .float(1.0)
            material.roughness = .float(0.0)
            material.baseColor = .color(.red)
    
            sphereComponent = ModelComponent(mesh: mesh,
                                        materials: [material])
    
            tetheringAnchor.components.set(sphereComponent!)
            arView.scene.anchors.append(tetheringAnchor)
    
            opacityAnimation()
        }
    
        func opacityAnimation() {
    
            UIView.animate(withDuration: 5.0,
                             animations: {
    
                self.material.metallic = .float(1.0)
                self.material.roughness = .float(0.0)
                self.material.baseColor = .color(.green)
    
                self.sphereComponent = ModelComponent(mesh: self.mesh,
                                                 materials: [self.material])
    
                self.tetheringAnchor.components.set(self.sphereComponent!)
                self.arView.scene.anchors.append(self.tetheringAnchor)
            })
        }
    }
    

提交回复
热议问题