在Sprite Kit iOS中使用一个图像精灵表

时间:2013-11-28 17:26:51

标签: ios sprite-kit sprite-sheet

我有一张sprite表,上面有我的精灵的动画图片。 如何将这些图像放入SKTextureAtlas(因此我可以在SKAction中制作动画)而不拆分单个文件? 我之前已经看过并完成过此操作,但是不使用SpriteKit和/或SKTextures。

如果不拆分文件,这是否可行? 最糟糕的情况:我需要将工作表分开制作图像。

过去我只是制作一个精灵大小和总精灵数的方法,这些精灵在代码中分离出来然后进行动画处理。


提前感谢您的帮助!

P.S。我是SpriteKit的新手,但不是游戏编程或iOS

2 个答案:

答案 0 :(得分:12)

感谢@ LearnCocos2D指导我使用textureWithRect:inTexture:,我在自定义Entity : SKSpriteNode类中创建了一个自定义初始化方法,允许使用包含所有图像的精灵表。我试图包含一些注释来解释代码。我有这个版本扫描x,因为我的动画是水平的。只能使用调用的方法更改Y.不在此版本的方法中。

确保将其放入界面!

alloc-initing的示例:

Entity *cookie = [[Entity alloc] initWithSpriteSheetNamed:@"cookie_sheet" withinNode:map sourceRect:CGRectMake(0, 0, 32, 32) andNumberOfSprites:6];

实体中的方法:SKSpriteNode

- (id) initWithSpriteSheetNamed: (NSString *) spriteSheet withinNode: (SKSpriteNode *) scene sourceRect: (CGRect) source andNumberOfSprites: (int) numberOfSprites {

    // @param numberOfSprites - the number of sprite images to the left
    // @param scene - I add my sprite to a map node. Change it to a SKScene
    // if [self addChild:] is used.

    NSMutableArray *mAnimatingFrames = [NSMutableArray array];

    SKTexture  *ssTexture = [SKTexture textureWithImageNamed:spriteSheet];
    // Makes the sprite (ssTexture) stay pixelated:
    ssTexture.filteringMode = SKTextureFilteringNearest;

    float sx = source.origin.x;
    float sy = source.origin.y;
    float sWidth = source.size.width;
    float sHeight = source.size.height;

    // IMPORTANT: textureWithRect: uses 1 as 100% of the sprite.
    // This is why division from the original sprite is necessary.
    // Also why sx is incremented by a fraction.

    for (int i = 0; i < numberOfSprites; i++) {
        CGRect cutter = CGRectMake(sx, sy/ssTexture.size.width, sWidth/ssTexture.size.width, sHeight/ssTexture.size.height);
        SKTexture *temp = [SKTexture textureWithRect:cutter inTexture:ssTexture];
        [mAnimatingFrames addObject:temp];
        sx+=sWidth/ssTexture.size.width;
    }

    self = [Entity spriteNodeWithTexture:mAnimatingFrames[0]];

    animatingFrames = mAnimatingFrames;

    [scene addChild:self];

    return self;
}

答案 1 :(得分:3)

您需要将每个动画帧作为单独的图像。然后,您可以使用SKAction为图像设置动画,可选择使用SKTextureAtlas。

所以是的,除非你编写一个自定义动画处理程序来手动更改动画精灵的纹理矩形,否则你必须拆分现有的工作表。您可以使用textureWithRect:inTexture:从spritesheet纹理创建较小的纹理。