Thanks to @LearnCocos2D guy for pointing me toward using textureWithRect:inTexture:
I made a custom init method within my custom Entity : SKSpriteNode
class which will allow the use of a sprite sheet with all images on it. I tried to include some comments to explain the code. I have this version scan the x as my animation is horizontal. Y can be changed only with the method called. Not in the method with this version.
Make sure to put it in the interface!
Example when alloc-initing:
Entity *cookie = [[Entity alloc] initWithSpriteSheetNamed:@"cookie_sheet" withinNode:map sourceRect:CGRectMake(0, 0, 32, 32) andNumberOfSprites:6];
The method in the Entity : 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;
}