Skip to content

Instantly share code, notes, and snippets.

@auycro
Last active September 22, 2016 06:56
Show Gist options
  • Save auycro/ad1f7adf4bfc0b413acf to your computer and use it in GitHub Desktop.
Save auycro/ad1f7adf4bfc0b413acf to your computer and use it in GitHub Desktop.
generate sprite from sprite sheet
//http://stackoverflow.com/questions/20271812/use-a-one-image-sprite-sheet-in-sprite-kit-ios
Entity *cookie = [[Entity alloc] initWithSpriteSheetNamed:@"cookie_sheet" withinNode:map sourceRect:CGRectMake(0, 0, 32, 32) andNumberOfSprites:6];
- (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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment