iOS SpriteKit如何使用应用程序捆绑包中的文件夹创build节点?

我试图创build一个随机怪物的精灵,我的图像存储在主包中引用的文件夹中。

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]; 

当我运行我的代码上面,我得到这个错误

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

如果我从主包中引用图像,代码将起作用。 我怎样才能从应用程序包中的文件夹中使用随机图像,并将其传递给SKSpriteNode?

在这种情况下,你不能使用spriteNodeWithImageNamed:方法。 你必须从绝对path自己创build纹理,并使用该纹理初始化你的精灵:

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

请注意,这样做将会失去使用spriteNodeWithImageNamed:所带来的性能优化spriteNodeWithImageNamed:如caching和更好的内存处理)

我build议把你的图像放在主包中,并使用如下特定的命名scheme:

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

或者,考虑使用纹理地图集 。

其实[SKSpriteNode spriteNodeWithImageNamed:]适用于我使用绝对path,至less在OSX 10.9上。 我正在开发一个项目,我需要访问应用程序包之外的资源,而且不需要SKTexture或NSImage就可以完成这项工作。

试试看:D

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