spritekit
Build 2D games and animations using SpriteKit. Use when creating game scenes with SKScene and SKView, adding sprites with SKSpriteNode, animating with SKAction sequences, simulating physics with SKPhysicsBody and contact detection, creating particle effects with SKEmitterNode, building tile maps, using SKCameraNode, or integrating SpriteKit scenes in SwiftUI with SpriteView.
What this skill does
# SpriteKit
Build 2D games and interactive animations for iOS 26+ using SpriteKit and
Swift 6.3. Covers scene lifecycle, node hierarchy, actions, physics, particles,
camera, touch handling, and SwiftUI integration.
## Contents
- [Scene Setup](#scene-setup)
- [Nodes and Sprites](#nodes-and-sprites)
- [Actions and Animation](#actions-and-animation)
- [Physics](#physics)
- [Touch Handling](#touch-handling)
- [Camera](#camera)
- [Particle Effects](#particle-effects)
- [SwiftUI Integration](#swiftui-integration)
- [Common Mistakes](#common-mistakes)
- [Review Checklist](#review-checklist)
- [References](#references)
## Scene Setup
SpriteKit renders content through `SKView`, which presents an `SKScene` -- the
root node of a tree that the framework animates and renders each frame.
### Creating a Scene
Subclass `SKScene` and override lifecycle methods. The coordinate system
origin is at the bottom-left by default.
```swift
import SpriteKit
final class GameScene: SKScene {
override func didMove(to view: SKView) {
backgroundColor = .darkGray
physicsWorld.contactDelegate = self
physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
setupNodes()
}
override func update(_ currentTime: TimeInterval) {
// Called once per frame before actions are evaluated.
}
}
```
### Presenting a Scene (UIKit)
```swift
guard let skView = view as? SKView else { return }
skView.ignoresSiblingOrder = true
let scene = GameScene(size: skView.bounds.size)
scene.scaleMode = .resizeFill
skView.presentScene(scene)
```
### Scale Modes
Use `.resizeFill` when the scene should adapt to view size changes (rotation,
multitasking). Use `.aspectFill` for fixed-design game scenes. `.aspectFit`
letterboxes; `.fill` stretches and may distort.
### Frame Cycle
Each frame follows this order:
1. `update(_:)` -- game logic
2. Evaluate actions
3. `didEvaluateActions()` -- post-action logic
4. Simulate physics
5. `didSimulatePhysics()` -- post-physics adjustments
6. Apply constraints
7. `didApplyConstraints()`
8. `didFinishUpdate()` -- final adjustments before rendering
Override only the callbacks where work is needed.
## Nodes and Sprites
Use `SKNode` (without a visual) as an invisible container or layout group.
Child nodes inherit parent position, scale, rotation, alpha, and speed.
`SKSpriteNode` is the primary visual node.
### Common Node Types
| Class | Purpose |
|-------|---------|
| `SKSpriteNode` | Textured image or solid color |
| `SKLabelNode` | Text rendering |
| `SKShapeNode` | Vector paths (expensive per draw call) |
| `SKEmitterNode` | Particle effects |
| `SKCameraNode` | Viewport control |
| `SKTileMapNode` | Grid-based tiles |
| `SKAudioNode` | Positional audio |
| `SKCropNode` / `SKEffectNode` | Masking / CIFilter |
| `SK3DNode` | Embedded SceneKit content |
### Creating Sprites
```swift
let player = SKSpriteNode(imageNamed: "hero")
player.position = CGPoint(x: frame.midX, y: frame.midY)
player.name = "player"
addChild(player)
```
### Drawing Order
Set `ignoresSiblingOrder = true` on `SKView` for better performance; SpriteKit
then uses `zPosition` to determine order. Without it, nodes draw in tree order.
```swift
background.zPosition = -1
player.zPosition = 0
foregroundUI.zPosition = 10
```
### Naming and Searching
Assign `name` to find nodes without instance variables. Use `childNode(withName:)`,
`enumerateChildNodes(withName:using:)`, or `subscript`. Patterns: `//` searches
the entire tree, `*` matches any characters, `..` refers to the parent.
```swift
player.name = "player"
if let found = childNode(withName: "player") as? SKSpriteNode { /* ... */ }
```
## Actions and Animation
`SKAction` objects define changes applied to nodes over time. Actions are
immutable and reusable. Run with `node.run(_:)`.
### Basic Actions
```swift
let moveUp = SKAction.moveBy(x: 0, y: 100, duration: 0.5)
let grow = SKAction.scale(to: 1.5, duration: 0.3)
let spin = SKAction.rotate(byAngle: .pi * 2, duration: 1.0)
let fadeOut = SKAction.fadeOut(withDuration: 0.3)
let remove = SKAction.removeFromParent()
```
### Combining Actions
```swift
// Sequential: run one after another
let dropAndRemove = SKAction.sequence([
SKAction.moveBy(x: 0, y: -500, duration: 1.0),
SKAction.removeFromParent()
])
// Parallel: run simultaneously
let scaleAndFade = SKAction.group([
SKAction.scale(to: 0.0, duration: 0.3),
SKAction.fadeOut(withDuration: 0.3)
])
// Repeat
let pulse = SKAction.repeatForever(
SKAction.sequence([
SKAction.scale(to: 1.2, duration: 0.5),
SKAction.scale(to: 1.0, duration: 0.5)
])
)
```
### Texture Animation
```swift
let walkFrames = (1...8).map { SKTexture(imageNamed: "walk_\($0)") }
let walkAction = SKAction.animate(with: walkFrames, timePerFrame: 0.1)
player.run(SKAction.repeatForever(walkAction))
```
Control the speed curve with `timingMode` (`.linear`, `.easeIn`, `.easeOut`,
`.easeInEaseOut`). Assign keys to actions for later access:
```swift
let easeIn = SKAction.moveTo(x: 300, duration: 1.0)
easeIn.timingMode = .easeInEaseOut
player.run(pulse, withKey: "pulse")
player.removeAction(forKey: "pulse") // stop later
```
## Physics
SpriteKit provides a built-in 2D physics engine. The scene's `physicsWorld`
manages gravity and collision detection.
### Adding Physics Bodies
```swift
// Circle body
player.physicsBody = SKPhysicsBody(circleOfRadius: player.size.width / 2)
player.physicsBody?.restitution = 0.3
// Static rectangle
ground.physicsBody = SKPhysicsBody(rectangleOf: ground.size)
ground.physicsBody?.isDynamic = false
// Texture-based body for irregular shapes
player.physicsBody = SKPhysicsBody(texture: player.texture!, size: player.size)
```
### Category and Contact Masks
Use bit masks to control collisions and contact callbacks:
```swift
struct PhysicsCategory {
static let player: UInt32 = 0b0001
static let enemy: UInt32 = 0b0010
static let ground: UInt32 = 0b0100
}
player.physicsBody?.categoryBitMask = PhysicsCategory.player
player.physicsBody?.contactTestBitMask = PhysicsCategory.enemy
player.physicsBody?.collisionBitMask = PhysicsCategory.ground
```
`categoryBitMask` identifies the body. `collisionBitMask` controls physics
response (bouncing). `contactTestBitMask` triggers `didBegin`/`didEnd`.
### Contact Detection
Implement `SKPhysicsContactDelegate` and set `physicsWorld.contactDelegate = self`
in `didMove(to:)`:
```swift
extension GameScene: SKPhysicsContactDelegate {
func didBegin(_ contact: SKPhysicsContact) {
let mask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
if mask == PhysicsCategory.player | PhysicsCategory.enemy {
queuePlayerHit()
}
}
}
```
Contact callbacks run during physics simulation. Make `queuePlayerHit()` set a
flag or append an event, then apply node/body/world mutations in `update(_:)`.
### Forces and Impulses
```swift
player.physicsBody?.applyForce(CGVector(dx: 0, dy: 50)) // continuous
player.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 200)) // instant
player.physicsBody?.applyAngularImpulse(0.5) // spin
```
Use `.applyImpulse` for jumps and projectile launches. Configure gravity with
`physicsWorld.gravity = CGVector(dx: 0, dy: -9.8)` and per-body with
`affectedByGravity`.
## Touch Handling
`SKScene` inherits from `UIResponder`. Override `touchesBegan`, `touchesMoved`,
`touchesEnded` on the scene. Use `nodes(at:)` to hit-test.
```swift
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let location = touch.location(in: self)
let tappedNodes = nodes(at: location)
if tappedNodes.contains(where: { $0.name == "playButton" }) {
startGame()
}
}
```
For node-level touch handling, subclass the node and set
`isUserInteractionEnabled = true`. That node then receives touches directly
instead of the scene.
## Camera
`SKCameraNode` cRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.