问题
Ok so I am conceptualizing for a game I want to make and have played a little bit but ran in to a problem. I am learning iOS programming and learning cocos2d also.
I have about 20 images. They are all the same size 64x64. Basically they are grouped as 5 different shapes (square, circle, etc.) each in 5 different colors. What I want to be able to do, is randomly drop them down the screen in portrait. There will only ever be one per column falling. There can be duplicates across the screen, I actually want that. While it is random, I want to control the introduction of a new color.
I have been really racking my brain to figure out how to do this. As I said, I am pretty new to this so any help would be really great.
If I could be so bold, can any answers be in a format to "Explain it like I'm 5 I have only been doing this for about 1 year"
回答1:
First, have a look at this tutorial about sprites sheets: it will show you how to create your sprite sheets and load them into memory. (Since the tutorial aims at building an animation, you can skip points 4 and 5).
Now, if you have your sprite sheets in place, what you do to create a sprite is:
CCSprite* sprite = [CCSprite spriteWithSpriteFrameName:@"frameName.png"];
and then you can add it to your layer/scene.
About the random selection: you can keep a list of image names (say, an NSArray
) and then randomly (i.e., use srand
to generate a random index) select the @"frameName.png"
value from it.
回答2:
When using Cocos2D the best way to use sprites is with Sprite Sheets. That is, a combination of two type of files:
- A plist file with all the coordinates of N sprites and all different data about the sprites, size, name, etc.
- A png file with all the sprites
You can make a sprite sheet with different types of software, like:
- Zwoptex
- Sprite Helper
- Sprite Packer
- Sprite Master
- Texture Packer
About performance, when using a sprite sheet you will need to use CCSpriteBatchNode, as the API documentation states (read here):
A CCSpriteBatchNode can reference one and only one texture (one image file, one texture atlas). Only the CCSprites that are contained in that texture can be added to the CCSpriteBatchNode. All CCSprites added to a CCSpriteBatchNode are drawn in one OpenGL ES draw call. If the CCSprites are not added to a CCSpriteBatchNode then an OpenGL ES draw call will be needed for each one, which is less efficient.
THe code to use Sprite Sheet:
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"sprite.plist"];
CCSpriteBatchNode *spriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"sprite.png"];
[self addChild:spriteSheet];
Hope this helps.
来源:https://stackoverflow.com/questions/9910011/cocos2d-load-random-image-from-sprite-sheet