我正在尝试创建一个随机怪物的 Sprite ,我的图像存储在主包中引用的文件夹中。
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?strong>
最佳答案
在这种情况下,您不能使用 spriteNodeWithImageNamed:
方法。您必须自己从绝对路径创建纹理并使用该纹理初始化您的 Sprite :
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...
或者,考虑使用 texture atlases .
关于iOS SpriteKit 如何使用应用程序包中文件夹中的图像创建节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20304507/