1

I have a class that inherits from CCNode. I want to override the adding of this class to a parent.

So if ClassA inherits CCNode, I add it like this [self addChild:ClassA];. ClassA contains 3 sprites and I want all 3 of those added when I add ClassA. Is there a way of doing this?

I looked into addChild and saw that it calls setParent on the child, so in ClassA I override setParent to do this:

- (void) setParent:(CCNode *)parent {
    [super setParent:parent];
    [parent addChild:_sprite1 z:kZClassA];
    [parent addChild:_sprite2 z:kZClassA];
    [parent addChild:_sprite3 z:kZClassA];
}

Seems kinda hacky to me? Is there a better way of doing this?

4

1 回答 1

1

此任务无需覆盖addChild。您所要做的就是在创建精灵时添加精灵ClassA。当您添加ClassA为节点的子节点时,也会自动添加 ClassA 子节点。(因为他们是 的孩子ClassA)。

假设你在 init 方法中创建你的精灵ClassA

- (id) init {
    if (self = [super init]) {
         // Create the sprites and then :
         [self addChild:sprite1]; // Add the sprite as a child of ClassA
         [self addChild:sprite2];
         [self addChild:sprite3];
    }

    return self;
}

然后添加classA到所需的节点(可能是一个CCLayer实例):

[self addChild:classAInstance]; // Where self is an instance of your desired CCNode
于 2013-08-18T15:16:54.497 回答