How to make a spritekit node change from one image to another

2.2k views Asked by At

I have an SKSpriteNode image with the code:

let Drake1 = SKSpriteNode(imageNamed: "Drake1")
    Drake1.position = CGPoint(x:self.frame.size.width/3, y:self.frame.size.height - 230)
    Drake1.zPosition = 2
    addChild(Drake1)

    //drake movement
    let moveRight = SKAction.moveByX(frame.size.width/2.8, y: 0, duration: 2)
    let moveLeft = SKAction.moveByX(-frame.size.width/2.8, y: 0, duration: 2)
    let moveBackAndForth = SKAction.repeatActionForever(SKAction.sequence([moveRight, moveLeft]))
    Drake1.runAction(moveBackAndForth)

What I want to do is, when the image is moving to the right, I want to replace the image with a different SKSpriteNode image, and when it moves back left, I want to use the original image, and repeat this forever. I am struggling with what the code should be for this.

1

There are 1 answers

0
BradzTech On

SpriteKit comes with a SKAction, setTexture, to instantaneously change a sprite's texture with relative ease. You can create an inline SKTexture object of each images, use them in SKActions, and add them to your sequence loop, like this:

let moveRight = SKAction.moveByX(frame.size.width/2.8, y: 0, duration: 2)
let moveLeft = SKAction.moveByX(-frame.size.width/2.8, y: 0, duration: 2)
let texRight = SKAction.setTexture(SKTexture(imageNamed: "Drake1r"))
let texLeft = SKAction.setTexture(SKTexture(imageNamed: "Drake1l"))
let moveBackAndForth = SKAction.repeatActionForever(SKAction.sequence([texRight, moveRight, texLeft, moveLeft]))
Drake1.runAction(moveBackAndForth)

Hopefully this works for you! Please note that if the textures are different sizes, you must add resize: Bool to setTexture's arguments.