Spritekit

作者 dpearson26998d90fd121a26無授權條款1.1K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫2 個月前更新

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.

AI 產生的概覽

指導使用 Apple SpriteKit 框架以 Swift 建構 2D 遊戲與動畫。

功能
此技能提供使用 SpriteKit 與 Swift 建構 2D 遊戲與互動式動畫的參考指引。內容涵蓋場景設定與生命週期、節點與精靈建立、SKAction 動畫、物理主體與接觸偵測、觸控處理、攝影機、粒子發射器,以及透過 SpriteView 將場景嵌入 SwiftUI。它也列出常見錯誤與審查清單,並附上一份關於圖磚地圖、紋理圖集、著色器、轉場與音訊的參考檔案。
適用情境
適用於撰寫或審查 SpriteKit 程式碼的情境,例如建立 SKScene 與 SKView、為精靈加入動畫、模擬物理效果,或將 SpriteKit 場景整合至 SwiftUI。對象為使用 Swift 的 iOS 遊戲與動畫開發。
執行需求
不含指令碼,僅為說明文件。需要具備 Swift 與 SpriteKit 框架的 Apple 平台開發環境,以及用於編輯粒子檔案與資源目錄的 Xcode。

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

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 = .resizeFillskView.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

ClassPurpose
SKSpriteNodeTextured image or solid color
SKLabelNodeText rendering
SKShapeNodeVector paths (expensive per draw call)
SKEmitterNodeParticle effects
SKCameraNodeViewport control
SKTileMapNodeGrid-based tiles
SKAudioNodePositional audio
SKCropNode / SKEffectNodeMasking / CIFilter
SK3DNodeEmbedded 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 = -1player.zPosition = 0foregroundUI.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 anotherlet dropAndRemove = SKAction.sequence([    SKAction.moveBy(x: 0, y: -500, duration: 1.0),    SKAction.removeFromParent()])
// Parallel: run simultaneouslylet scaleAndFade = SKAction.group([    SKAction.scale(to: 0.0, duration: 0.3),    SKAction.fadeOut(withDuration: 0.3)])
// Repeatlet 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 bodyplayer.physicsBody = SKPhysicsBody(circleOfRadius: player.size.width / 2)player.physicsBody?.restitution = 0.3
// Static rectangleground.physicsBody = SKPhysicsBody(rectangleOf: ground.size)ground.physicsBody?.isDynamic = false
// Texture-based body for irregular shapesplayer.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.playerplayer.physicsBody?.contactTestBitMask = PhysicsCategory.enemyplayer.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))      // continuousplayer.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 200))   // instantplayer.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 controls the visible portion of the scene. Add it as a child and assign to scene.camera.

swift
let cameraNode = SKCameraNode()addChild(cameraNode)camera = cameraNodecameraNode.position = CGPoint(x: frame.midX, y: frame.midY)

Following a Character

Update the camera position in didSimulatePhysics() or use constraints:

swift
override func didSimulatePhysics() {    cameraNode.position = player.position}
// Constrain camera to world boundslet xRange = SKRange(lowerLimit: frame.midX, upperLimit: worldWidth - frame.midX)let yRange = SKRange(lowerLimit: frame.midY, upperLimit: worldHeight - frame.midY)cameraNode.constraints = [SKConstraint.positionX(xRange, y: yRange)]

Camera Zoom and HUD

Scale the camera node inversely: setScale(0.5) zooms in 2x, setScale(2.0) zooms out 2x. Nodes added as children of the camera stay fixed on screen (HUD elements):

swift
let scoreLabel = SKLabelNode(text: "Score: 0")scoreLabel.position = CGPoint(x: 0, y: frame.height / 2 - 40)scoreLabel.fontName = "AvenirNext-Bold"scoreLabel.fontSize = 24cameraNode.addChild(scoreLabel)

Particle Effects

SKEmitterNode generates particle effects. Design emitters in Xcode's SpriteKit Particle File editor (.sks) or configure in code.

swift
// Load from fileguard let emitter = SKEmitterNode(fileNamed: "Fire") else { return }emitter.position = CGPoint(x: frame.midX, y: 100)addChild(emitter)

One-Shot Emitters

Set numParticlesToEmit for finite effects and remove after completion:

swift
func spawnExplosion(at position: CGPoint) {    guard let explosion = SKEmitterNode(fileNamed: "Explosion") else { return }    explosion.position = position    explosion.numParticlesToEmit = 100    addChild(explosion)
    let wait = SKAction.wait(forDuration: TimeInterval(explosion.particleLifetime))    explosion.run(SKAction.sequence([wait, .removeFromParent()]))}

Set targetNode to the scene so particles stay in world space when the emitter moves: emitter.targetNode = self.

SwiftUI Integration

SpriteView embeds a SpriteKit scene in SwiftUI.

swift
import SwiftUIimport SpriteKit
struct GameView: View {    @State private var scene: GameScene = {        let s = GameScene()        s.size = CGSize(width: 390, height: 844)        s.scaleMode = .resizeFill        return s    }()
    var body: some View {        SpriteView(scene: scene)            .ignoresSafeArea()    }}

SpriteView Options

Pass options: [.allowsTransparency] for transparent backgrounds, .shouldCullNonVisibleNodes for offscreen culling, or .ignoresSiblingOrder for zPosition-based draw order. Use debugOptions: [.showsFPS, .showsNodeCount] during development.

Communicating Between SwiftUI and the Scene

Pass data through a shared @Observable object. Store the scene in @State to avoid re-creation on view re-renders:

swift
@Observable final class GameState {    var score = 0    var isPaused = false}
struct GameContainerView: View {    @State private var gameState = GameState()    @State private var scene = GameScene()
    var body: some View {        SpriteView(scene: scene, isPaused: gameState.isPaused)            .onAppear { scene.gameState = gameState }    }}

Common Mistakes

Creating a new scene on every SwiftUI re-render

swift
// DON'T: Scene is recreated on every body evaluationvar body: some View {    SpriteView(scene: GameScene(size: CGSize(width: 390, height: 844)))}
// DO: Create once and reuse@State private var scene = GameScene(size: CGSize(width: 390, height: 844))var body: some View {    SpriteView(scene: scene)}

Adding a child node that already has a parent

A node can only have one parent. Remove from the current parent first or create a separate instance. Adding a node that already has a parent crashes.

Forgetting to set contactTestBitMask

swift
// DON'T: Bodies collide but didBegin is never calledplayer.physicsBody?.categoryBitMask = PhysicsCategory.playerenemy.physicsBody?.categoryBitMask = PhysicsCategory.enemy
// DO: Set contactTestBitMask to receive contact callbacksplayer.physicsBody?.contactTestBitMask = PhysicsCategory.enemy

Using SKShapeNode for performance-critical rendering

SKShapeNode uses a separate draw call per instance. Prefer SKSpriteNode with a texture for repeated elements to enable batched rendering.

Not removing nodes that leave the screen

swift
// DON'Tenemy.run(SKAction.moveBy(x: -800, y: 0, duration: 3.0))addChild(enemy)
// DO: Remove after leaving the visible areaenemy.run(SKAction.sequence([    SKAction.moveBy(x: -800, y: 0, duration: 3.0),    SKAction.removeFromParent()]))addChild(enemy)

Setting physicsWorld.contactDelegate too late

Set physicsWorld.contactDelegate = self in didMove(to:), not in update(_:) or after a delay.

Review Checklist

  • Scene subclass overrides didMove(to:) for setup, not init
  • scaleMode chosen appropriately for the game's design
  • ignoresSiblingOrder set to true on SKView for performance
  • zPosition used consistently when ignoresSiblingOrder is enabled
  • Physics contactDelegate set in didMove(to:)
  • Category, collision, and contact bit masks configured correctly
  • contactTestBitMask set for any pair needing didBegin/didEnd callbacks
  • Contact callbacks queue changes instead of mutating the physics world directly
  • Static bodies use isDynamic = false
  • SKShapeNode avoided in performance-critical paths; SKSpriteNode preferred
  • Actions that move nodes offscreen include .removeFromParent() in sequence
  • One-shot emitters remove themselves after particle lifetime expires
  • Emitter targetNode set when particles should stay in world space
  • Scene stored in @State when used with SpriteView in SwiftUI
  • Texture atlases used for related sprites to reduce draw calls
  • update(_:) uses delta time for frame-rate-independent movement
  • Nodes removed from parent before being re-added elsewhere

References

來源與署名

來源:dpearson2699/swift-ios-skills位於skills/spritekit提交8d90fd1

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架

更多來自 dpearson2699/swift-ios-skills 的技能

Widgetkit

dpearson2699

指導實作、審查與改進 iOS、iPadOS、watchOS 與 CarPlay 上的 WidgetKit 小工具與控制項。

Software Development1.1K2 個月前更新

Weatherkit

dpearson2699

指導 iOS 開發者使用 WeatherService 取得 WeatherKit 預報、警報與署名資訊。

Software Development1.1K2 個月前更新

Vision Framework

dpearson2699

Implement computer vision features including text recognition (OCR), face detection, barcode scanning, image segmentation, object tracking, and document scanning in iOS apps. Covers both the modern Swift-native Vision API (iOS 18+) and legacy VNRequest patterns, VisionKit DataScannerViewController for live camera scanning, and CoreMLRequest/VNCoreMLRequest for custom model inference. Use when adding OCR, barcode scanning, face detection, or custom Core ML model inference with Vision.

待分類1.1K2 個月前更新

Tipkit

dpearson2699

Implement and review Apple TipKit feature-discovery UI for iOS 17+ apps. Use when adding or auditing in-app tips, contextual help, coach marks, Tip, TipView, popoverTip, rules, events, actions, display frequency, testing overrides, reusable tip identifiers, or iOS 18+ TipGroup and CloudKit tip sync; avoid for generic SwiftUI navigation or layout outside tip presentation.

待分類1.1K2 個月前更新

Tabletopkit

dpearson2699

指導使用 TabletopKit 在 visionOS 上打造多人空間桌遊,涵蓋棋具、座位、動作與 RealityKit 算繪。

Software Development1.1K2 個月前更新

Swiftui Webkit

dpearson2699

指導在 iOS 26 及更新版本的 SwiftUI App 中使用 WebKit for SwiftUI 嵌入與控制網頁內容。

Software Development1.1K2 個月前更新