6

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

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?

4

2 回答 2

6

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

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

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

我建议将您的图像放在主包中并使用如下特定的命名方案:

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

或者,考虑使用纹理图集

于 2013-11-30T19:21:16.223 回答
0

实际上 [SKSpriteNode spriteNodeWithImageNamed:] 使用绝对路径对我有用,至少在 OSX 10.9 上是这样。我正在做一个项目,我需要访问应用程序包之外的资源,它在不需要 SKTexture 或 NSImage 的情况下就可以完成这项工作。

试试看 :D

NSString *imagePath = @"~/Desktop/test.png";
SKSpriteNode *test = [SKSpriteNode spriteNodeWithImageNamed:[imagePath stringByExpandingTildeInPath]];
于 2014-07-23T17:59:11.327 回答