I have this declared on my main class:
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"atlas.plist"];
CCSpriteBatchNode *batchNode = [CCSpriteBatchNode batchNodeWithFile:#"atlas.png"];
now I am on another class and I want to create a new batchNode but get spriteFrames from atlas, that was declared on the main class. How do I do that? Do I need to put these same lines again on my other class? By doing so, will I have redundant images imported to the sharedSpriteFrameCache? My idea is to save memory, not wasted.
Any clues? thanks.
You don't need to call [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"atlas.plist"]; again assuming you haven't removed these sprite frames.
You will need to create another batch node to put sprites on.
If you were to try and add the sprite frames to the cache again, you wouldn't waste space, the sprite frames would only be added once, but you would waste time while cocos2D parses through the file and determines if each sprite frame has indeed already been added.
Related
While creating a cocos2d iOS game, there are several options to add spritesheets - CCTextureCache::addImageAsync, CCSpriteFrameCache::addSpriteFramesWithFile, etc. - what is the difference between using these different ways to add a spritesheet?
Similarly, to load a sprite, we can call CCSprite::spriteWithSpriteFrameName or CCSprite::spriteWithFile or CCSpriteBatchNode::batchNodeWithTexture, etc. What is the difference between using these techniques?
Thanks
Anand
Load sprite frames, this also loads the textures:
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"file.plist"];
Use sprite frames:
CCSprite* sprite = [CCSprite spriteWithSpriteFrameName:#"frame.png"];
Add the sprite to a batch node:
CCSpriteBatchNode* batchNode = [CCSpriteBatchNode batchNodeWithTexture:sprite.texture];
[batchNode addChild:sprite];
The batchNodeWithFile works too if you use the same image file of the sprite. If the sprite was initialized with a spriteframe, it'll be the texture atlas image (ie "file.png").
addImageAsync is only needed if you want to load your texture on another thread, usually to animate the loading screen. You'll still have to add the sprite frames afterwards.
CCSprite spriteWithFile creates a sprite from a single image file. Those can be batched too but it's better to use a texture atlas with sprite frames.
Anyone that can give any hint of the smartest way to do a main loop animation? I don't want to use CCAnimation because I want to control the animations frame by frame.
Shall I store the sprite rect (relative to the sprite sheet) for each individual frame in an array, and then look up the suiting rect in each animation step? I tried to find out how this is done in CCAnimation, but I didn't succeed...
How to get the rect for each frame at initialization?
How to set the rect at each animation step?
Do I need to use CCSpriteBatchNode? I guess not, eh?
Cannot crealry understand, why you don't want to use CCAnimation, but anyway, to get answer for your questions you can check creation code of the CCSprite instance. Then, check creation of CCSpriteFrame instance. There you will find the answer for at least your first question.
Actually if you just want to manage animation frames differently from CCAnimate, you can just store array of CCSpriteFrames and show them as you want(in CCAnimate action these frames are just changed one by one in equal time intervals).
And if you do not want to show more than one frame of your animation, there is no difference will you use CCSpriteBatchNode or not. It saves a lot of processor time if you need to draw several parts of one texture, as it draws them in one draw call instead of send draw message to all of these sprites.
As you want animate sprite frame by frame I think using CCSpriteBatchNode would be a better option as it give you frame by frame access of animation.Making plist of sprites using any tool like "Zwoptex" will give an efficient way to animate using CCSpriteBatchNode.
Hope you know the animation using plist file with CCSpriteBatchNode.
I did the following with inspiration from Morions answer:
In the game tick function:
_animationFrames.legFrame = (_animationFrames.legFrame + 1) % _animationFrames.legFrames.count;
[_legs setDisplayFrame: [_animationFrames.legFrames objectAtIndex: _animationFrames.legFrame]];
And in the init function:
CCSpriteBatchNode *spriteSheet = [CCSpriteBatchNode
batchNodeWithFile:#"Player.png"];
[self addChild:spriteSheet];
_animationFrames.legFrames = [[NSMutableArray array] retain];
for(int i = 0; i <= 15; ++i)
{
[_animationFrames.legFrames addObject:
[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:
[NSString stringWithFormat:#"Player_legs-%d.png", i]]];
}
_legs = [CCSprite spriteWithSpriteFrameName:#"Player_legs-0.png"];
[_sprite addChild: spriteSheet];
[spriteSheet addChild:_legs z:1];
I don't know if this is possible, but I would like to create one big texture atlas and use it on all classes of the application.
Can one CCSpriteBatchNode be used for multiple classes?
Suppose I create this on the main class
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"atlasGeral.plist"];
self.batchNodeGeneral = [CCSpriteBatchNode batchNodeWithFile:#"atlasGeral.png"];
[self addChild:self.batchNodeGeneral];
and I have another class creating CCLayers on the main class, that is initialized, before using CCSpriteBatchNode, like this:
-(id) init
{
if( (self=[super init])) {
self.bg = [CCSprite spriteWithFile: #"cCircularBG.png"];
[self addChild:self.bg];
self.dr = [CCSprite spriteWithFile: #"cCircularDR.png"];
[self addChild:self.dr];
}
return self; // self is a CCLayer
}
can this be optimized using the self.batchNodeGeneral from the main class? My idea is to replace these two sprites and others with something like [CCSprite spriteWithSpriteFrameName:...
thanks
I'm not entirely sure I follow, but I'm pretty sure the answer is yes.
CCSpriteBatchNode doesn't have anything to do with classes, it has to do with assets. The important restriction on the use of batch nodes is that every sprite in the batch needs to reference the same texture atlas. So it is perfectly fine to have one batch node for your entire application and have every gameplay class add its own sprites to that batch. This can turn into a practical issue if your texture atlas becomes larger than the maximum texture size on your target hardware (see iOS device specs for details), but if you still want to have global batches and lots of assets it's not too hard to create a batch pool indexed by texture ID, create one batch node per atlas, and whenever you create a new sprite add it to the appropriate batch.
Honestly, I feel like the whole batch node thing is a terrible kludge on Cocos2D's part that could be made almost completely transparent to developers while still retaining its efficiency, but maybe this opinion is not entirely fair since I haven't dug around in the rendering code to understand their motivations. I guess it would mess with expectations of how depth sorting works, etc., but still I don't understand why batching objects for render is made the programmer's responsibility, it should be done by the engine.
Edit to add possible solution:
-(id) initWithMainClass:(MainClass*)mc
{
if( (self=[super init])) {
self.bg = [CCSprite spriteWithSpriteFrameName: #"cCircularBG.png"];
[mc.batchNodeGeneral addChild:self.bg];
self.dr = [CCSprite spriteWithSpriteFrameName: #"cCircularDR.png"];
[mc.batchNodeGeneral addChild:self.dr];
}
return self; // self is a CCLayer
}
`
So when you initialize one of the other classes, you pass the main class instance as a parameter so you can access its fields. Or make the main/manager class a singleton or find another architecture suitable to your needs.
i am using the CCSpriteFrameCache a lot but cant understand somthing about it.
can i load many .plist to the cache at the start of my game ? or the CCSpriteFrameCache has ONLY one plist at a time ?
by now there is a sprite which is a child of a CCSpriteBatchNode ,that is been created many times during the game , with different images. so every time i create a new sprite i do this:
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:[NSString stringWithFormat:#"cand%i.plist",stage]];
candySheet = [CCSpriteBatchNode batchNodeWithFile:[NSString stringWithFormat:#"cand%i.png",stage]];
[self addChild:candySheet];
sprite1 = [CCSprite spriteWithSpriteFrameName:[NSString stringWithFormat:#"cand%i.png",1]];
is it ok ?
now lets say i have 2 spriteSheets, and 2 .plist, and i want to load both of them on my init , and add 2 sprites, each to be a child of one CCSpriteBatchNode and render images for each sprite from his own spriteSheet and Plist. but i get error then that :
CCSprite is not using the same texture id
so, i understand that each time i have to load to the cache the plist that i need at that specific time ????
thanks.
Someone asked a similar thing earlier.
You cannot make sprites children of the same CCSpriteBatchNode if they are not from the same spritesheet.
You need to create a new CCSpriteBatchNode for each spritesheet you use (by spritesheet I mean the combined image file and .plist file)
The CCSpriteFrameCache is a single cache shared across all your scenes and classes. When you call this method:
[CCSpriteFrameCache sharedSpriteFrameCache]
You are not making a new CCSpriteFrameCache object everytime, there is just ONE instance. You store all your loaded spritesheets in this single cache. So you could load 2 spritesheets into the cache like so:
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"sheet1.plist"]; [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"sheet2.plist"];
You then need to create a CCSpriteBatchNode for EACH spritesheet, you cannot have more than one sheet in a batch node:
CCSpriteBatchNode *spriteSheet1 = [CCSpriteBatchNode batchNodeWithFile:#"sheet1.pvr.ccz"];
CCSpriteBatchNode *spriteSheet2 = [CCSpriteBatchNode batchNodeWithFile:#"sheet2.pvr.ccz"];
You can then add both of these batch nodes to a layer if you wish. Sprites added to batch nodes must be from the spritesheet that batch node is using.
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"some.plist"];
The above line takes quite a chunk of time even if the sprite frames are already loaded/cached. So make sure to avoid doing this unless you're absolutely certain that these sprite frames haven't been cached before, like at the beginning of the game or after purging the sprite frame cache.
I have 3 question.
How to keep fps rate constant(almost) in cocos2d.When lots of CCSprite created and removed within a small interval like (5-8) per second is it possible to keep frame rate lmost constant??
Is [self removeChild:sprite cleanup:YES] is enough or i should also use
CCTexture2D *texture = [sprite texture];
[[CCTextureCache sharedTextureCache] removeTexture: texture];
The following Part of code is responsible for my frame drop.How to accomplish same task in better way-
id fadeout = [CCFadeOut actionWithDuration:1.4f];
id call = [CCCallFunc
actionWithTarget:self
selector:#selector(RemoveSmashedSprite:)];
CCSequence* sequence= [CCSequence actions:fadeout, call, nil];
[smash runAction:sequence];
and
-(void)RemoveSmashedSprite:(id)sender
{
CCSprite *sp = (CCSprite *)sender;
[self removeChild:sp cleanup:YES];
}
This is called 5-8 times per second.So the frame rate goes down.Can any one help me.
I am guessing that the "smashed sprite" in question is probably one of a number of sprites visible on the screen, more than likely sharing the same texture (part of a sprite sheet perhaps, or all the same image, etc?).
If this is the case, I would recommend allocating the number of sprites your games requires to have on screen and rather than "destroy" (remove them, re-create them) you should "re-use them".
Store a reference to all the CCSprite's in an NSMutableArray, populate this array with the number of sprites you think is appropriate (how many sprites are removed per second? how many sprites are added per second? how many sprites are on the screen to start? - use the answers to these questions to determine the most appropriate size of your array).
Then, rather than removing the sprite as a child, simply [sprite setVisible: NO] to hide it, then ... when you need to display a new one on screen, use the next "available" (hidden) sprite in the array (keep track of the last "used" sprite with an index, and simply increment it by 1 to find the next "available". Once the index exceeds the bounds, reset it to 0 - at this point, that sprite should have been "smashed"). Once you have the next "available" sprite, change it's properties (position, scale, texture?, visibility) and apply any actions that are appropriate (don't forget to "stop all actions" on it when "smashing it" - this is what "cleanup: YES" does).
If your game does not allow you to go around in a "circle" like this, because the user decides what may or may not be visible by interacting with the sprites in a varied order then you can store a reference to the "smashed sprites" in a separate array (while keeping them in the original array as well - then you can just pick anyObject from the "unused" array, remove it from that array and then alter it as mentioned above).
This should reduce your frame rate drops dramatically, as you won't be creating and destroying sprites all the time.
Another thing that may be occurring is that you are using different images, and each image is stored separately (image1.png, image2.png, image3.png) and the creation/destruction of these is causing the textures to be removed and re-added ... to resolve this, create a sprite sheet and add the sprite sheet to the Texture Cache, then create your images with 'spriteFromSpriteCacheName:#"image1.png"'