Ale*_*one 6 objective-c ios ios7 sprite-kit skspritenode
我正在尝试创建一个随机怪物的精灵,我的图像存储在主束中引用的文件夹中.
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];
Run Code Online (Sandbox Code Playgroud)
当我运行上面的代码时,我收到此错误
SKTexture: Error loading image resource: "random_monster.png"
Run Code Online (Sandbox Code Playgroud)
如果我从主包中引用图像,则代码有效.如何使用应用程序包中的文件夹中的随机图像并将其传递给SKSpriteNode?
在这种情况下,您无法使用该spriteNodeWithImageNamed:方法.您必须自己从绝对路径创建纹理并使用该纹理初始化您的精灵:
NSImage *image = [[NSImage alloc] initWithContentsOfFile:absolutePath];
SKTexture *texture = [SKTexture textureWithImage:image];
SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithTexture:texture];
Run Code Online (Sandbox Code Playgroud)
请注意,这样做会丢失使用时带来的性能优化spriteNodeWithImageNamed:(例如缓存和更好的内存处理)
我建议将您的图像放在主包中,并使用如下的特定命名方案:
monster_001.png
monster_002.png
monster_003.png
etc...
Run Code Online (Sandbox Code Playgroud)
或者,考虑使用纹理图集.
| 归档时间: |
|
| 查看次数: |
4842 次 |
| 最近记录: |