CODEX
How to Generate Lightning in Swift [Recursively]
Generate realistic-looking lightning strikes in Swift
Published in
7 min readJan 16, 2021
Learn how to generate realistic lightning in Swift.
Disclaimer: This post contains affiliate links.
The Setup
To get started, create a Game App in Xcode. Remove Actions.sks
file and remove the hello label from GameScene.sks
. Then erase excess code in GameScene.swift
file to make it look like this:
import SpriteKit
import GameplayKitclass GameScene: SKScene {
override func didMove(to view: SKView) {
self.backgroundColor = .black
}
}
Drawing a Single Line
A lightning strike consists of small paths or line segments that are connected to form the lightning strike.
First off, we want to be able to draw a line from point A to point B. The following code snippet will return a line:
func createLine(pointA: CGPoint, pointB: CGPoint) -> SKShapeNode {
let pathToDraw = CGMutablePath()
pathToDraw.move(to: pointA)
pathToDraw.addLine(to: pointB)
let line = SKShapeNode()
line.path = pathToDraw
line.glowWidth = 1
line.strokeColor = .white
return line
}