Skip to content

Instantly share code, notes, and snippets.

@drewolbrich
Last active January 31, 2024 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drewolbrich/00e5491ca734065e53c5872dc7420bbb to your computer and use it in GitHub Desktop.
Save drewolbrich/00e5491ca734065e53c5872dc7420bbb to your computer and use it in GitHub Desktop.
An entity that supports animated changes in opacity
// Important: You may want to use this newer `Entity` extension instead: https://gist.github.com/drewolbrich/1e9d3da074c8a1d5ca93721124b97596
import Foundation
import RealityKit
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