Skip to main content
ClaudeWave
Skill732 estrellas del repoactualizado 15d ago

spritekit

This Claude Code skill provides comprehensive guidance for building 2D games and interactive animations on iOS using SpriteKit and Swift. Use it when creating game scenes with SKScene and SKView, adding visual sprites with SKSpriteNode, animating with SKAction sequences, simulating physics with SKPhysicsBody and contact detection, creating particle effects with SKEmitterNode, implementing camera controls with SKCameraNode, handling touch input, or integrating SpriteKit scenes into SwiftUI applications with SpriteView.

Instalar en Claude Code
Copiar
git clone --depth 1 https://github.com/dpearson2699/swift-ios-skills /tmp/spritekit && cp -r /tmp/spritekit/skills/spritekit ~/.claude/skills/spritekit
Después abre una sesión nueva de Claude Code; el skill carga automáticamente.

SKILL.md

# 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?.c
accessorysetupkitSkill

Discover and configure Bluetooth and Wi-Fi accessories using AccessorySetupKit. Use when presenting a privacy-preserving accessory picker, defining discovery descriptors for BLE or Wi-Fi devices, handling accessory session events, migrating from CoreBluetooth permission-based scanning, or setting up accessories without requiring broad Bluetooth permissions.

activitykitSkill

Implement, review, or improve Live Activities and Dynamic Island experiences in iOS apps using ActivityKit. Use when building real-time updating widgets for the Lock Screen and Dynamic Island — delivery tracking, sports scores, ride-sharing status, workout timers, media playback, or any time-sensitive information that updates in real time. Also use when working with ActivityKit, ActivityAttributes, Activity lifecycle (request/update/end), Dynamic Island layouts (compact/minimal/expanded), push-to-update Live Activities, or Lock Screen live widgets.

adattributionkitSkill

Measure ad effectiveness with privacy-preserving attribution using AdAttributionKit. Use when registering ad impressions, handling attribution postbacks, updating conversion values, implementing re-engagement attribution, configuring publisher or advertiser apps, or replacing SKAdNetwork with AdAttributionKit for ad measurement.

alarmkitSkill

Implement AlarmKit alarms and countdown timers for iOS and iPadOS with Lock Screen, Dynamic Island, StandBy, and paired Apple Watch system UI. Covers AlarmManager scheduling, AlarmAttributes and AlarmPresentation, AlarmButton stop and snooze actions, authorization, state observation, countdown widget-extension handoff, and Live Activity integration. Use when building wake-up alarms, countdown timers, or alarm-style alerts that need Apple's system alarm experience.

app-clipsSkill

Build iOS App Clips with invocation URLs, App Clip Codes, NFC, QR codes, Safari banners, Maps, Messages, target setup, App Store Connect experiences, size/capability constraints, NSUserActivity routing, SKOverlay promotion, App Group/keychain handoff, ephemeral notifications, location confirmation, and full-app migration. Use when creating App Clips or wiring App Clip invocation, experience configuration, or full-app handoff.

app-intentsSkill

Implement App Intents for Siri, Shortcuts, Spotlight, widgets, Control Center, and Apple Intelligence on iOS. Covers AppIntent actions, AppEntity and EntityQuery models, AppShortcutsProvider phrases, IndexedEntity Spotlight indexing, WidgetConfigurationIntent, SnippetIntent, and assistant schemas. Use when exposing app actions or entities to system surfaces.

app-store-optimizationSkill

Optimize App Store product pages for search visibility and conversion. Use for App Store Optimization (ASO), keyword research, app name/subtitle/keyword-field strategy, conversion-focused descriptions and promotional text, screenshot captions and ordering, Custom Product Pages with assigned search keywords, In-App Events, Product Page Optimization tests, localized metadata, ratings/review strategy, and in-app review prompt timing with RequestReviewAction or AppStore.requestReview. Also use when routing ASO vs App Store review, privacy/ATT, or StoreKit implementation boundaries.

app-store-reviewSkill

Prepare for App Store review and prevent rejections. Covers App Store review guidelines, app rejection reasons, PrivacyInfo.xcprivacy privacy manifest requirements, required API reason codes, in-app purchase IAP and StoreKit rules, App Store Guidelines compliance, ATT App Tracking Transparency, EU DMA Digital Markets Act, HIG compliance checklist, app submission preparation, review preparation, metadata requirements, entitlements, widgets, and Live Activities review rules. Use when preparing for App Store submission, fixing rejection reasons, auditing privacy manifests, implementing ATT consent flow, configuring StoreKit IAP, or checking HIG compliance.