Alex Borsody
Alex Borsody

Reputation: 2040

Simple Gif like animation with Spritekit

I can't really find a simple solution for this, every example I see only shows very complex solutions, but all I want is 2-3 images that cycle so it appears as if it is animated. Same effect as an animated Gif. For now I have this to create an image

MonsterNode = SKSpriteNode(imageNamed: "MonsterNode_GameScene")

but how would I set MonsterNode variable to an animation of this sort? I am really looking for the very least amount of code needed to achieve this.

Upvotes: 3

Views: 4397

Answers (2)

Gurmeet Khalsa
Gurmeet Khalsa

Reputation: 136

I was getting the same issue of big red X. So instead of defining the monsterNode in code. I created the monstor on sks screen by dragging first image of animation from atlas folder. Then assign it a name: monsterNode from properties section. Here's the code

var runAnimation = [SKTexture]()

override func didMove(to view: SKView) {
    let runAtlas = SKTextureAtlas(named: "run")
    for index in 1...runAtlas.textureNames.count{
        let textureName = String.init(format: "run%1d", index)
        runAnimation.append(SKTexture(imageNamed: textureName))
    }
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let monsterNode = self.childNode(withName: "monsterNode")
    if(monsterNode != nil){
        let animation = SKAction.animate(with: runAnimation, timePerFrame: 0.1)
        monsterNode?.run(SKAction.repeatForever(animation))
     }       
}

Upvotes: 0

WangYudong
WangYudong

Reputation: 4423

The main idea is to use animateWithTextures for this task. You need to set all the frames that the sprite needs to animated and the displayed time of each frame. Then use repeatActionForever to run the animation loop.

// Add 3 frames
let f0 = SKTexture.init(imageNamed: "MonsterNode_GameScene_0")
let f1 = SKTexture.init(imageNamed: "MonsterNode_GameScene_1")
let f2 = SKTexture.init(imageNamed: "MonsterNode_GameScene_2")
let frames: [SKTexture] = [f0, f1, f2]

// Load the first frame as initialization
monsterNode = SKSpriteNode(imageNamed: "MonsterNode_GameScene_0")
monsterNode.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))

// Change the frame per 0.2 sec
let animation = SKAction.animateWithTextures(frames, timePerFrame: 0.2)
monsterNode.runAction(SKAction.repeatActionForever(animation))

self.addChild(monsterNode)

Upvotes: 5

Related Questions