问题
OK, this one's got me screaming to the walls... so bear with me please.
I started to code a simple game using the SpriteKit template in Xcode.
I added two PNGs to a folder named Stage01.atlas
and dragged that to the project. Can't remember if which option I chose, because it appears as a blue folder icon in the project navigator (perhaps because it has an extension?).
Next, I instantiated several sprites using
[[SKSpriteNode alloc] initWithImageNamed:@"My_Image_Name_Without_The_@2x_Or_Extension"];
At first, it didn't work , because I forgot to enable texture atlases in the build settings. Then, it worked like a charm, but...
Next, I added a third PNG to the atlas to display a new kind of sprite.
The new sprite was nowhere to be seen.
I try a clean install: delete the app from the device, clean, build.
Now all the sprites are rendered as a white quad with aback border and a big, red "X" inside. I also get console messages along the lines of:
SKTexture: Error loading image resource: "My_Image_Name_Without_The_@2x_Or_Extension"
I tried removing the .atlas folder and re-adding it, both as "Create groups for any added folders" and "Create folder references for any added folders" (this can cause a resource to be placed in a subfolder instead of the bundle root, so it usually matters for UIImage etc.), to no avail.
I replaced the sprite creation code with this:
SKTexture* texture = [SKTexture textureWithImageNamed:name];
SKSpriteNode* body = [[SKSpriteNode alloc] initWithTexture:texture];
...and placed a breakpoint to see if the texture is nil
. It isn't.
So, what gives?
Side note: The "spaceship" texture bundled with the template renders fine.
Side note 2: Someone create the tag "spritekit" (SO doesn't let me use it 'because it already exists' but it doesn't come up as a suggestion).
回答1:
To use texture atlas textures you first need to load the texture atlas:
SKTextureAtlas* atlas = [SKTextureAtlas atlasNamed:@"Stage01"];
Then you can create sprites from its textures:
SKTexture* texture = [atlas textureNamed:@"My_Image_..."];
SKSpriteNode* body = [SKSpriteNode spriteNodeWithTexture:texture];
The fact that initially this worked may have been because the images were added without the .atlas generated, and even if you subsequently remove the images from the project they will remain in the deployed app bundle because Xcode doesn't remove resources from an app bundle. So Sprite Kit was using the non-atlas images initially, and not it can't find those and it won't look for them in a texture atlas automatically, nor will it auto-load the atlas.
来源:https://stackoverflow.com/questions/19862828/sprite-kit-textures-acting-funny