Would anyone consider the following scenario and give me a suggestion : I am implementing a basic cocos2d game with one GameplayLayer which has got one CCSpriteBatchNode. I have one GameObject:CCNode which has 3 CCSprites like so:
CCSprite *bodySprite;
CCSprite *hairSprite;
CCSprite *eyesSprite;
When initializing GameObject
I am adding the sprites to GameObject
as its children like so:
[self addChild:bodySprite];
[self addChild:hairSprite];
[self addChild:eyesSprite];
This way I can change the position, rotation etc. of the node (GameObject
) and all the sprites will be affected by the change BUT there is a major performance issue when I add more than one GameObject
s to the scene as "each sprite draws itself, which means one additional draw call per sprite".
To fix the performance issue, after reading this post, I decided to add the GameObject
's sprites to GameplayLayer
's CCSpriteBatchNode
upon initialization like so :
[[GameplayLayer sharedGameplayLayer].sceneSpriteBatchNode addChild:bodySprite];
[[GameplayLayer sharedGameplayLayer].sceneSpriteBatchNode addChild:hairSprite];
[[GameplayLayer sharedGameplayLayer].sceneSpriteBatchNode addChild:eyesSprite];
Only now, I have to set the position of the GameObject
's sprites one by one, instead of
self.position = ...
I have to use
bodySprite.position = ...
hairSprite.position = ...
eyesSprite.postion =...
Which is a tedious change and I lose one of the biggest benefits of having designed my GameObject
as a composition of sprites.
The question : Is there a way to use the node's postion to affect the composing sprites positions , can I add them as children to BOTH the GameObject
and sceneSpriteBatchNode
? If not what is the right approach, is it setting the positions of the sprites one by one ?
First, "major performance" is relative. If that's your only sprite, you will not see any effect of sprite batching them. It's a different story if you have dozens of them on the screen at the same time.
You can not add a node to two parents at the same time.
What you could do is to create a "container" sprite. Create a CCSprite with texture (same as sprite batch node texture) and a CGRectEmpty as texture rect. That makes the sprite not draw anything and you can use it as if it were a CCNode added to the CCSpriteBatchNode.
Then you can add your sprites to that invisible sprite and use the container sprite to affect position, rotation, etc of its child sprites like you used to.