Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a child have multiple parents in Sprite Kit?

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?

like image 603
user3576196 Avatar asked Dec 16 '25 15:12

user3576196


1 Answers

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]];

like image 148
Jesse Rusak Avatar answered Dec 19 '25 06:12

Jesse Rusak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!