Reputation: 275
I'm working on a Sprite-Kit game and I have a menu that displays all the levels. I've created a locked image that I want to display on levels that are locked, below is the code:
SKSpriteNode *locked = [SKSpriteNode spriteNodeWithImageNamed:@"Locked.png"];
locked.position = CGPointMake(0, 0);
locked.zPosition = 2.0;
locked.size = CGSizeMake(20, 20);
Then I want to display it on all the levels until they are unlocked. This is the code:
SKSpriteNode *level2 = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(40, 40)];
level2.position = CGPointMake(CGRectGetMidX(self.frame)-75, CGRectGetMidY(self.frame)+100);
[level2 addChild:locked];
[_levels addObject:level2];
[self addChild:level2];
But when I tried to display it on the third level:
SKSpriteNode *level3 = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(40, 40)];
level3.position = CGPointMake(CGRectGetMidX(self.frame)-30, CGRectGetMidY(self.frame)+100);
[level3 addChild:locked];
[_levels addObject:level3];
[self addChild:level3];
I ran into an error because locked already had a parent.
Can a child have multiple parents? If so where am I going wrong?
Upvotes: 3
Views: 516
Reputation: 57168
A SKNode
can only have one parent. (Its parent
method can only return one thing, after all.)
It also conforms to NSCopying, which means you can copy a node if you need more than one with the copy
method. So, you might try something like [level3 addChild:[locked copy]];
Upvotes: 5