Reputation: 2418
I am wanting to use the same sprite multiple times in Cocos2d 3.0
at the moment when i do this i get the following error
"reason: 'child already added to another node. It can't be added again'"
i have looked at other responses to similar questions here on stacker overflow and they state that spriteBatchNode is required. However this has depreciated in version 3.0.
Make local instances of the sprites *( i have used nodes here as i get an error when trying to add them to the array (Incompatible pointer types assigning to 'CCSprite *' from 'CCNode '))
CCNode *_sprite1;
CCNode *_sprite2;
CCNode *_sprite3;
CCNode *_sprite4;
I currently Have an array where sprites(CCNodes)are added
_array1 = @[_sprite1,_sprite2,_sprite3,_sprite4];
_array2 = @[_sprite1,_sprite2,_sprite3,_sprite4];
I would then make a call to spawn the sprites
-(void)spawnSprites1
{
int randomNumber = [self generateRandomNumberBetweenMin:0 Max:_array1.count-1];
CCSprite *sprite = [_array1 objectAtIndex:randomNumber];
sprite.position = ccp(_size.width +100 , _size.height *0.26);
sprite.zOrder = DrawingOrderPlayer;
[_physicsNode addChild:sprite];
CCLOG(@"content size = %f",_size.height);
}
-(void)spawnSprites2
{
int randomNumber = [self generateRandomNumberBetweenMin:0 Max:_array2.count-1];
CCSprite *sprite = [_array2 objectAtIndex:randomNumber];
sprite.position = ccp(_size.width +100 , _size.height *0.26);
sprite.zOrder = DrawingOrderPlayer;
[_physicsNode addChild:sprite];
CCLOG(@"content size = %f",_size.height);
}
if the same sprite is drawn from either i receive the above crash log.
Does anybody know how to resolve this issue in Cocos2d v3.0
Thanks
Upvotes: 0
Views: 112
Reputation: 2418
Problem resolved, rather the pulling sprites out of an array randomly, it was just as easy to randomly pull them using a switch statement.
Upvotes: 0
Reputation: 64477
Each new sprite needs to be a new CCSprite instance. Since cocos2d doesn't implement NSCopying yet, the easiest way is to initialize new sprites using one template instance's texture, like so:
CCSprite* newSprite = [CCSprite spriteWithTexture:templateSprite.texture];
Then assign any property from the templateSprite
to newSprite
if the copy should have the same value(s).
Upvotes: 2