Lab 057 – Using Opacity Component with Particle Emitters

We can use Opacity Component on an entity with a Particle System to fade out all particles together.

This can be helpful when we need to show and hide a particle system. For example, when deactivating a rain system in a world. We can dial down the opacity, then deactivate the entity once the value reaches zero.

This lab just changes the value of the Opacity Component on the entity with the Particle Emitter Component.

Lab Code

struct Lab057: View {

    @State private var value: Float = 1

    var body: some View {
        RealityView { content in

            let subject = Entity()
            subject.name = "Particles"
            content.add(subject)

            var particleSystem = ParticleEmitterComponent()
            particleSystem.isEmitting = true
            particleSystem.speed = 0.01
            particleSystem.emitterShape = .sphere
            particleSystem.emitterShapeSize = [0.3, 0.3, 0.3]

            particleSystem.mainEmitter.birthRate = 25
            particleSystem.mainEmitter.size = 0.1
            particleSystem.mainEmitter.color = .constant(.single(.stepRed))

            subject.components.set(particleSystem)

        } update: { content in

            if let subject = content.entities.first?.findEntity(named: "Particles") {
                let opacity = OpacityComponent(opacity: value)
                subject.components.set(opacity)
            }

        }
        .toolbar {
            ToolbarItem(placement: .bottomOrnament, content: {
                HStack {
                    Slider(value: $value,
                           in: 0.0...1.0,
                           minimumValueLabel: Image(systemName: "circle"),
                           maximumValueLabel: Image(systemName: "circle.fill"),
                           label: {
                        Text("Opacity")
                    })
                    .frame(width: 240)
                }
            })
        }
    }

}

Support our work so we can continue to bring you new examples and articles.

Download the Xcode project with this and many more labs from Step Into Vision.

Questions or feedback?