Last active
June 10, 2024 16:41
-
-
Save drewolbrich/00e5491ca734065e53c5872dc7420bbb to your computer and use it in GitHub Desktop.
An entity that supports animated changes in opacity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import RealityKit | |
// *********************************************************************** | |
// Important: You may want to use this newer `Entity` extension instead, | |
// which includes a completion handler for the `Entity/setOpacity` method: | |
// https://gist.github.com/drewolbrich/1e9d3da074c8a1d5ca93721124b97596 | |
// *********************************************************************** | |
extension Entity { | |
/// The opacity value applied to the entity and its descendants. | |
/// | |
/// `OpacityComponent` is assigned to the entity if it doesn't already exist. | |
var opacity: Float { | |
get { | |
return components[OpacityComponent.self]?.opacity ?? 1 | |
} | |
set { | |
if !components.has(OpacityComponent.self) { | |
components[OpacityComponent.self] = OpacityComponent(opacity: newValue) | |
} else { | |
components[OpacityComponent.self]?.opacity = newValue | |
} | |
} | |
} | |
/// Sets the opacity value applied to the entity and its descendants with optional animation. | |
/// | |
/// `OpacityComponent` is assigned to the entity if it doesn't already exist. | |
func setOpacity(_ opacity: Float, animated: Bool, duration: TimeInterval = 0.2, delay: TimeInterval = 0) { | |
guard animated else { | |
self.opacity = opacity | |
return | |
} | |
if !components.has(OpacityComponent.self) { | |
components[OpacityComponent.self] = OpacityComponent(opacity: 1) | |
} | |
let animation = FromToByAnimation(name: "Entity/setOpacity", to: opacity, duration: duration, timing: .linear, isAdditive: false, bindTarget: .opacity, delay: delay) | |
do { | |
let animationResource: AnimationResource = try .generate(with: animation) | |
playAnimation(animationResource) | |
} catch { | |
assertionFailure("Could not generate animation: \(error.localizedDescription)") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment