I have 3 different classes Tree
, Fruit
, and Basket
. Each of them have their own CCSprite
member that I access through getSprite( )
( each class has its own getSprite( )
). Also, each class has a draw( )
method which sets the CCSprite
’s texture, position, and other CCSprite
related stuff. When I make an instance of these classes, I always need to addChild( )
each of these sprites in the main layer. Nothing’s actually wrong with it but I want it so that each draw( )
method would be the one handling the addChild( )
method to the main layer.
My code is like this:
// Tree.cpp
#include "Tree.h"
#include "cocos2d.h"
using namespace cocos2d;
Tree::Tree( ) {
draw( );
}
CCSprite * Tree:getSprite( ) {
return m_TreeSprite;
}
void Tree::draw( ) {
m_TreeSprite = CCSprite::create( "tree.png" );
m_TreeSprite -> setPosition ( 100, 100 );
}
/*
* The other classes have similar structure. Will take a long long post if I write them all.
*/
// MainLayer.cpp
void MainLayer::drawScreenObjects( ) {
m_Tree = Tree( );
this -> addChild( m_Tree.getSprite( ) );
m_Basket = Basket( );
this -> addChild( m_Basket.getSprite( ) );
}
I want it so that the draw( ) method could look similar to this:
void Tree::draw( ) {
m_TreeSprite = CCSprite::create( "tree.png" );
m_TreeSprite -> setPosition( 100, 100 );
MainLayer -> addChild( m_TreeSprite );
}
Solutions I am thinking of are
- Passing references to the MainLayer to every class and have a member variable hold that reference.
- Making all classes inherit from CCNode so that they can have children of their own.
Any other possible solutions? I just feel my current setup is dirty and unstable. Thanks in advance.