I’m pretty new to cocos2d development and ran into a problem of getting a valid boundingBox and contentSize, and running CCActions on CCNodes with children. It seemed to me that if your CCNode has children and you call boundingBox (for example) on that CCNode, you should get a CGRect of that CCNode that takes into account its children. Or is it that I’m just organizing my code incorrectly..?
Anyway, I’ve written a small category for CCNode that seems to return the correct boundingBox and contentSize and runs actions on its children.
@implementation CCNode(Children)
- (CGRect)boundingBoxC {
if (self.boundingBox.size.width != 0 || self.boundingBox.size.height != 0) {
return self.boundingBox;
}
CGRect holderRect = CGRectZero;
for (int i = 0; i < self.children.count; i++) {
CCNode *node = [self.children objectAtIndex:i];
holderRect = CGRectUnion(holderRect, node.boundingBoxC);
}
return holderRect;
}
- (CGSize)contentSizeC {
return self.boundingBoxC.size;
}
- (void)runActionC:(CCAction *)action {
[self runAction:action];
for (int i = 0; i < self.children.count; i++) {
id action2 = [action copy];
CCNode *node = [self.children objectAtIndex:i];
[node runActionC:action2];
[actions2 release];
}
}
@end
I’d love to get some feedback on this. For example, I started by trying to use the name boundingBox instead of boundingBoxC, but wasn’t confident that that was good practice (it involved swizzling). Or if there’s a more comprehensive, elegant solution to this, I’d love to hear about it.
Thanks!
Think of nodes as reference points, not boxes, and you can see why the default behaviour is as it is. Your code looks clean (and glad to see it’s in a category rather than a subclass!) and I can’t see any problems with your logic. Definitely don’t override built-in methods (unless you really need to), as 1) you could create conflicts and 2) future developers will be confused.