iOS SpriteKit 如何使用应用程序包中文件夹中的图像创建节点?

标签 ios objective-c ios7 sprite-kit skspritenode

我正在尝试创建一个随机怪物的 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?

最佳答案

在这种情况下,您不能使用 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/

相关文章:

ios - TableView 的开始位置在模拟器中是错误的,并且在 Storyboard中不一样

ios - 没有m3u8扩展名的swift stream hls

iphone - 对于iphone开发,需要学习cocoa touch吗?

database - 在 ios7 中读取预填充的 Sqlite.db

uiscrollview - 使 UIGestureRecognizer 响应已经在进行中并被另一个识别器识别的手势

ios - 在我的应用程序中访问 iCloud 联系人时导致 iOS 崩溃

ios - CGContext 缩放至视网膜

ios - 编译错误 : redefinition of label openURL

ios - 如何在 Objective-C 中将 __NSCFString 转换为 NSData

objective-c - 如何用触摸手势控制 CAKeyframeAnimation?