All articles

How to Switch Between Idle, Run, Jump, and Attack Animations in SpriteKit

Keep animations running smoothly, give attacks priority, and reuse the same playback logic across your game.

A preview using the Desert Ruins sprite frames. Idle and run loop. A slash interrupts the jump animation, which starts again if the character is still airborne.

Watch the SpriteKit animation demo

Getting a character to run through a sequence of images is an early milestone in a SpriteKit game. Making that character switch smoothly between standing, running, jumping, and attacking takes a little more planning.

In Desert Ruins, our SpriteKit sample, the explorer needs four animation states. Idle and running should loop. Jumping and slashing should play once. An attack needs to take priority while it is active, and a character that keeps running should continue its current animation.

I built Scroller2d to make common SpriteKit work reusable. This example shows the animation helper alongside the small amount of game logic that decides which animation to play.

Start with texture animation

SpriteKit provides SKAction.animate to play an array of textures. You supply the frames in playback order and specify how long each frame appears. Apple’s texture animation documentation describes this behavior.

For a running animation, that can look like this.

let running = SKAction.animate(
    with: runningFrames,
    timePerFrame: 0.08
)

player.run(
    .repeatForever(running),
    withKey: "pose"
)

Here, runningFrames is an ordered [SKTexture] array prepared when loading the character. See how Desert Ruins loads animation frames from a texture atlas.

The action works well when started once. If you start it again on every update, however, you continually replace its progress. The character can appear stuck near the beginning of the animation.

The scene needs to remember what is already playing.

Give the character an animation state

Desert Ruins represents its four poses with an enum.

private enum Pose: String {
    case idle
    case run
    case jump
    case slash
}

private var pose: Pose?

It also keeps the loaded frames and playback timings.

private var poses: [Pose: [SKTexture]] = [:]
private var timings: [Pose: TimeInterval] = [:]

Preparing these collections during character setup keeps texture loading out of the frame update loop. It also lets each animation have its own speed. The explorer’s running animation uses shorter frame intervals than its idle animation.

Change the animation when the state changes

The following is an adapted version of the sample’s setPose method. This first version uses standard SpriteKit actions.

private func setPose(_ next: Pose) {
    guard pose != next,
          let frames = poses[next],
          let first = frames.first else {
        return
    }

    pose = next

    player.removeAction(forKey: "pose")
    player.texture = first

    let animation = SKAction.animate(
        with: frames,
        timePerFrame: timings[next] ?? 0.1
    )

    let shouldLoop = next == .idle || next == .run
    let action = shouldLoop
        ? SKAction.repeatForever(animation)
        : animation

    player.run(action, withKey: "pose")
}

The guard prevents an unchanged state from restarting its animation. It also leaves the current animation alone if the requested frame sequence is missing or empty.

Using the "pose" key gives character animation a consistent place to run. Replacing that action lets other actions on the player continue independently.

Idle and running repeat until another pose takes over. Jumping and slashing play through their frames once, then hold their final texture until the game selects another pose.

Decide which state has priority

Each update, the game determines the requested pose from its current gameplay state.

if clock < slashUntil {
    setPose(.slash)
} else if !grounded {
    setPose(.jump)
} else if direction == 0 {
    setPose(.idle)
} else {
    setPose(.run)
}

These variables come from the game’s movement and combat logic. grounded tracks contact with the terrain, direction represents movement input, and slashUntil marks the end of the current attack animation.

The order gives slashing the highest priority. If the player attacks while airborne, the slash can finish before the scene selects the jumping pose again.

When the attack window ends, the same update logic chooses the next animation. A moving character returns to running after landing. A stationary character returns to idle.

Because setPose checks the current pose, the scene can make this decision every frame without restarting an unchanged animation.

Use Scroller2d for reusable playback

Desert Ruins uses the same state selection with Scroller2d’s manualAnimate helper. Inside its GameScene, which subclasses AppSharedSceneBase, the playback portion becomes this.

let frequency: animationFrequency =
    next == .idle || next == .run
        ? .foreverAutomatically
        : .once

let action = SKAction.manualAnimate(
    frames: frames,
    skScene: self,
    frameRange: nil,
    idlePerFrameWait: timings[next] ?? 0.1,
    frequency: frequency
)

player.run(action, withKey: "pose")

The helper accepts loaded textures, a frame range, frame timing, repetition behavior, and an optional delay between cycles. An atlas-name overload retrieves textures through the scene’s texture cache.

That gives characters and other animated objects a shared playback interface. The game still chooses the state and its priority. The helper packages the repeated work of constructing the animation action.

In Desert Ruins, some animation timing values also come from the character configuration. That makes it possible to adjust those timings through data as the character’s behavior takes shape.

Try it in Desert Ruins

The downloadable sample includes the explorer’s idle, running, jumping, and slashing artwork, the Swift source, and an editable LevelEditor workspace.

Run the game, hold a movement arrow, jump, and press Slash. Then open GameScene.swift and look for setPose to see how those inputs become animation changes.

Run and edit Desert Ruins

Three animation experiments

Run the unmodified sample once for comparison. Rebuild and run after each change, then restore the original before moving on.

1. Slow down the run cycle

In the iOS demo’s DesertRuins/Levels/DesertRuins.plist, find the dune_explorer character’s waitPerAnimationFrame dictionary. Change its move value from 0.08 to 0.16 seconds per frame. Hold a movement arrow on flat ground. The explorer should cover ground at the same speed while the running frames cycle half as often.

2. Reproduce a stuck run animation

In GameScene.swift, remove just pose != next, from the guard in setPose. Keep both frame checks. Hold a movement arrow and watch the explorer’s feet. The action restarts every update, so the sprite can appear stuck on its first running frame. Restore the check and repeat to see the full loop play.

3. Give the jump animation priority

Jump and press Slash early in the jump. With the original code, the slash animation takes over in midair. In GameScene.swift, find the setPose call in step and replace it with this version, which checks whether the explorer is airborne first.

if !grounded {
    setPose(.jump)
} else if clock < slashUntil {
    setPose(.slash)
} else {
    setPose(direction == 0 ? .idle : .run)
}

Repeat the jump and slash. The jump pose should stay visible while airborne. If the slash window is still open when you land, the slash pose can appear then. This edit changes which pose is shown. The attack input and hit timing still run as before.

Where Scroller2d saves work

The game still chooses the pose. Scroller2d’s animation helper can load an atlas through the scene cache and build a playback action from the chosen frame range and timing. Reuse the same pose switch for multiple characters and keep the artwork and frame timing in their definitions.