如何在spritekit游戏中更改图像

时间:2014-03-17 15:10:03

标签: ios sprite-kit

我在游戏中有一个角色(spritekit),它被定义为:

 -(id)initWithSize:(CGSize)size{
    if (self = [super initWithSize:size]) {
       SKTexture* characterTexture1 = [SKTexture textureWithImageNamed:@"firstappearancecharacter1"];
        characterTexture1.filteringMode = SKTextureFilteringNearest;
        SKTexture* characterTexture2 = [SKTexture textureWithImageNamed:@"firstappearancecharacter2"];
        characterTexture2.filteringMode = SKTextureFilteringNearest;
        SKTexture* characterTexture3 = [SKTexture textureWithImageNamed:@"firstappearancecharacter3"];
        characterTexture3.filteringMode = SKTextureFilteringNearest;

        SKAction* thataction = [SKAction repeatActionForever:[SKAction animateWithTextures:@[characterTexture1, characterTexture2,characterTexture3]timePerFrame:0.2]];

我希望在索引时更改该字符的显示:

NSInteger _myindex;

达到一定值。现在,我希望每次索引达到一些值,如5,10,15,20,25 ......然后角色将改变他的显示,这是一组新的外观图像:

..textureWithImageNamed:@"2nd_appearance_character1"];
...
...textureWithImageNamed:@"2nd_appearance_character3"];

但我应该在哪里以及如何制作?

1 个答案:

答案 0 :(得分:1)

有更好的方法,将所有纹理存储在数组中;

NSMutableArray* textureArray = [NSMutableArray array];
for (int i = 1; i =< 3; i++) {
    //dynamically create an array of textures
    NSString* string = [NSString stringWithFormat:@"firstappearancecharacter%d", i];
    SKTexture* tmp = [SKTexture textureWithImageNamed:string];
    tmp.filteringMode = SKTextureFilteringNearest;

    [textureArray addObject:tmp];
}

SKAction* action = [SKAction repeatActionForever:[SKAction animateWithTextures:textureArray timePerFrame:0.2]];

现在针对您的问题,首先检查增量索引是否可被5整除,如果是,则从数组中动态获取纹理。

// to get the correct texture every 5 increments
if (self.myindex % 5 == 0) {
    int x = self.myindex/5.0;
    SKTexture* texture = [textureArray ObjectAtIndex:x];
}

与您的评论如下:

我会创建一个具有所有不同外观的NSArray,并再次动态创建纹理。

NSArray* appearanceArray = [NSArray arrayWithObjects:@"firstappearancecharacter", @"secondappearancecharacter", @"thirdappearancecharacter", nil];

然后将上面的for循环用于另一个for循环:

for (int j = 0; j < [appearanceArray count]; j++) {
     NSMutableArray* textureArray = [NSMutableArray array];

     for (int i = 1; i =< 3; i++) {
        //dynamically create an array of textures
        //then replace the NSString inside the above for loop with the below:
        NSString* string = [NSString stringWithFormat:@"%@%d", [appearanceArray objectAtIndex:j], i];
        SKTexture* tmp = [SKTexture textureWithImageNamed:string];
        tmp.filteringMode = SKTextureFilteringNearest;

        [textureArray addObject:tmp];
     }
}