Sprite-Kit Change Image of Node when screen gets touched

浪子不回头ぞ 提交于 2019-12-22 10:38:22

问题


There is a hero that is controlled by tapping on the screen. I want the hero too look a little different every time the screen gets touched.

What I did is setting up two images that are a little different. I want the image of the hero to be changed when there is a touch event.

Until now I set up an array to save the information in but it kinda won't work out:

 NSMutableArray *heroFrames = [NSMutableArray array];

NSString* textureName = nil;

if (UITouchPhaseBegan) {
    textureName = @"hero1.gif";
}
else  {
    textureName = @"hero2.gif";
}

    SKTexture* texture = [SKTexture textureWithImageNamed:textureName];
    [heroFrames addObject:texture];

[self setHeroFrames:HeroFrames];

self.hero = [SKSpriteNode spriteNodeWithTexture:[_heroFrames objectAtIndex:1]];

I get an exception when running this.. Any other idea how to achieve my problem?

Thanks guys!


回答1:


Welcome to SO.

Try this code:

#import "MyScene.h"

@implementation MyScene
{
    BOOL myBool;
    SKSpriteNode *hero;
    SKTexture *texture1;
    SKTexture *texture2;
}

-(id)initWithSize:(CGSize)size
{
    if (self = [super initWithSize:size])
    {
        myBool = false;
        texture1 = [SKTexture textureWithImageNamed:@"hero1.gif"];
        texture2 = [SKTexture textureWithImageNamed:@"hero2.gif"];
        hero = [SKSpriteNode spriteNodeWithTexture:texture1];
        hero.position = CGPointMake(200, 150);
        [self addChild:hero];
    }
    return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if(myBool == true)
    {
        hero.texture = texture1;
        myBool = false;
    } else
    {
        hero.texture = texture2;
        myBool = true;
    }
}


来源:https://stackoverflow.com/questions/23014744/sprite-kit-change-image-of-node-when-screen-gets-touched

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!