user1483652 user1483652 - 2 months ago 15
iOS Question

How to change a characters image in 'touchbegan' in spritekit?

I'm currently using Sprite Kit and Xcode to design a game. My character is usually in the state of running which consists of two images - code below:

bobSKTexture* Texture1 = [SKTexture textureWithImageNamed:@"bob1"];
bobTexture1.filteringMode = SKTextureFilteringNearest;
SKTexture* bobTexture2 = [SKTexture textureWithImageNamed:@"bob2"];
bobTexture2.filteringMode = SKTextureFilteringNearest;

SKAction* run = [SKAction repeatActionForever:[SKAction animateWithTextures:@[birdTexture1, birdTexture2] timePerFrame:0.2]];

_bob = [SKSpriteNode spriteNodeWithTexture:birdTexture1];
[_bob setScale:2.0];
_bob.position = CGPointMake(self.frame.size.width / 4, CGRectGetMidY(self.frame));
[_bob runAction:run];


I want the image to change when a touch to the screen happens, only for a short amount of time and then I want it to return to the above code. How can I accomplish this?

Answer

As Jānis K said, it would be even easier to do like this when you want the image to change:

[_bob removeAllActions];
_bob.texture = [SKTexture textureWithImageNamed:NEW_TEXTURE];
[self performSelector:@selector(resetAnimation) withObject:nil afterDelay:2.0f];

NEW_TEXTURE is the name of the texture/image you want it to change to.

self would be the scene or wherever you call the code to make _bob

This is the resetAnimation method, defined in your scene or wherever you call the code to make _bob:

- (void)resetAnimation
    {
        SKAction* run = [SKAction repeatActionForever:[SKAction animateWithTextures:@[birdTexture1, birdTexture2] timePerFrame:0.2]];
        [_bob runAction:run];
    }