SpriteKit gives inbuilt great animated particles, we can take advantage of it to create nice animated splash screen or scratch card win celebration screen!
Let’s begin
Create a project with SwiftUI. Now add particle file from File > New > File… > SpriteKit Particle File. I have taken Fireflies particle file. It will look like this ?
I have done changes in this file in birthrate and texture (bokeh) which is inbuilt. You can play with this file and do required changes.
Make Scene!
Now create SKScene
file from the particle file. Here I have added particle file as SKEmitterNode
in SKScene
.
// | |
// FirefilesScene.swift | |
// AKSwiftUIParticles | |
// | |
// Created by Ashish Kakkad on 30/04/22. | |
// | |
import SpriteKit | |
class FirefilesScene: SKScene { | |
let snowEmitterNode = SKEmitterNode(fileNamed: "Firefiles.sks") | |
override func didMove(to view: SKView) { | |
guard let snowEmitterNode = snowEmitterNode else { return } | |
snowEmitterNode.particleSize = CGSize(width: 30, height: 30) | |
snowEmitterNode.particleLifetime = 5 | |
snowEmitterNode.particleLifetimeRange = 10 | |
addChild(snowEmitterNode) | |
} | |
override func didChangeSize(_ oldSize: CGSize) { | |
guard let snowEmitterNode = snowEmitterNode else { return } | |
snowEmitterNode.particlePosition = CGPoint(x: size.width/2, y: size.height) | |
snowEmitterNode.particlePositionRange = CGVector(dx: size.width, dy: size.height) | |
} | |
} |
Display in SwiftUI
Now display this scene into the SwiftUI View. Here, I am adding whole code with a bonus text animation ?
// | |
// AKParticleView.swift | |
// AKSwiftUIParticles | |
// | |
// Created by Ashish Kakkad on 30/04/22. | |
// | |
import SwiftUI | |
import SpriteKit | |
struct AKParticleView: View { | |
@State var animatedText: String = "" | |
@State private var flag = true | |
var scene: SKScene { | |
let scene = FirefilesScene() | |
scene.scaleMode = .resizeFill | |
scene.backgroundColor = .clear | |
return scene | |
} | |
var body: some View { | |
ZStack { | |
SpriteView(scene: scene, options: [.allowsTransparency]) | |
.ignoresSafeArea() | |
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity) | |
VStack() { | |
Spacer() | |
Text(animatedText) | |
.font(.title) | |
.fontWeight(.light) | |
.animation(.spring()) | |
.padding() | |
} | |
} | |
.onAppear{ | |
animatedText = "" | |
"Ashish Kakkad".enumerated().forEach { index, character in | |
DispatchQueue.main.asyncAfter(deadline: .now() + Double(index) * 0.2) { | |
animatedText += String(character) | |
} | |
} | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
AKParticleView() | |
} | |
} |
Code
The source code is available at my Github – ashishkakkad8/AKSwiftUIParticles.
Conclusion
Let me know if you have any questions, comments, or feedback – either via Twitter.
Stay Safe At Home. Learn Something New. Share To The World.
Happy Coding ?