IOS SpriteKit how to create a node with an image from a folder in an application bundle?

I am trying to create a random monster sprite where my images are stored in the folder referenced by the main folder.

NSString* bundlePath = [[NSBundle mainBundle] bundlePath]; NSString* resourceFolderPath = [NSString stringWithFormat:@"%@/monsters", bundlePath]; NSArray* resourceFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:resourceFolderPath error:nil]; NSInteger randomFileIndex = arc4random() % [resourceFiles count]; NSString* randomFile = [resourceFiles objectAtIndex:randomFileIndex]; SKSpriteNode* tile = [SKSpriteNode spriteNodeWithImageNamed:randomFile]; 

When I run my code above, I get this error

 SKTexture: Error loading image resource: "random_monster.png" 

The code works if I refer to an image from the main package. How to use a random image from a folder in the application bundle and transfer it to SKSpriteNode?

+6
source share
2 answers

In this case, you cannot use the spriteNodeWithImageNamed: method. You yourself need to create a texture from an absolute path and initialize your sprite using this texture:

 NSImage *image = [[NSImage alloc] initWithContentsOfFile:absolutePath]; SKTexture *texture = [SKTexture textureWithImage:image]; SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithTexture:texture]; 

Note that doing so will lose the performance optimization used with spriteNodeWithImageNamed: (for example, caching and improved memory handling).

I recommend putting your images in the main set and using a specific naming scheme as follows:

 monster_001.png monster_002.png monster_003.png etc... 

As an alternative, consider using texture atlases .

+6
source

Actually [SKSpriteNode spriteNodeWithImageNamed:] works for me, using an absolute path, at least on OSX 10.9. I am working on a project where I need to access resources outside the application package, and it does the work without the need for SKTexture or NSImage.

Try it: D

 NSString *imagePath = @"~/Desktop/test.png"; SKSpriteNode *test = [SKSpriteNode spriteNodeWithImageNamed:[imagePath stringByExpandingTildeInPath]]; 
0
source

Source: https://habr.com/ru/post/959090/


All Articles