Reputation: 2315
In the cocos2d engine, there is a method to add an object as a child of another.
So for example in this line of code in a Game.m file:
CCMenu *menu = [CCMenu menuWithItems:pauseButton, nil];
pauseButton.position = ccp(s.width/2 - pauseButton.contentSize.width/2, (-s.height/2)
+ pauseButton.contentSize.height/2);
[self addChild:menu z:100];
You can see the menu instance of CCMenu is added as a child to the class object of Game. What does this actually do? Is it for memory purposes?
Upvotes: 0
Views: 190
Reputation: 64477
Cocoa and Qt use this kind of hierarchy as well, where you can add one view as a child to another view. It has nothing to do with memory usage, it's main purpose is to have a clear order of responsibility (in Cocoa: responder chain).
In User Interfaces, the lowermost views get the first chance to react to user input. If a view doesn't react to user input it will pass on responsibility to its parent. In Cocos2D this isn't used however and it becomes mainly a system to position nodes relative to each other and to group nodes together so that they're all drawn on the same "depth layer".
The disadvantage of a tree-like hierarchy like this is that you can not easily iterate over all nodes in a scene without recursing into every child tree.
Upvotes: 1
Reputation: 18149
This kind of hierarchy system helps organize and reference your game components. And display them.
Game.m
is your scene, and it will be displaying your game elements. However, it has no idea what those elements are. So the scene has a list of children, and it will "display" them (sprites, buttons, labels, etc...). So you add a child to the scene as a way to tell the scene that this child needs to be displayed, because it is a visual element.
Upvotes: 1