Note that there are some explanatory texts on larger screens.

plurals
  1. POAccess the Main Scene / Layer from a class
    primarykey
    data
    text
    <p>I have 3 different classes <code>Tree</code>, <code>Fruit</code>, and <code>Basket</code>. Each of them have their own <code>CCSprite</code> member that I access through <code>getSprite( )</code> ( each class has its own <code>getSprite( )</code> ). Also, each class has a <code>draw( )</code> method which sets the <code>CCSprite</code>'s texture, position, and other <code>CCSprite</code> related stuff. When I make an instance of these classes, I always need to <code>addChild( )</code> each of these sprites in the main layer. Nothing's actually wrong with it but I want it so that each <code>draw( )</code> method would be the one handling the <code>addChild( )</code> method to the main layer.</p> <p>My code is like this:</p> <pre><code>// 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 -&gt; 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 -&gt; addChild( m_Tree.getSprite( ) ); m_Basket = Basket( ); this -&gt; addChild( m_Basket.getSprite( ) ); } </code></pre> <p>I want it so that the <code>draw( )</code> method could look similar to this:</p> <pre><code>void Tree::draw( ) { m_TreeSprite = CCSprite::create( "tree.png" ); m_TreeSprite -&gt; setPosition( 100, 100 ); MainLayer -&gt; addChild( m_TreeSprite ); } </code></pre> <p>Solutions I am thinking of are</p> <ol> <li>Passing references to the <code>MainLayer</code> to every class and have a member variable hold that reference.</li> <li>Making all classes inherit from CCNode so that they can have children of their own.</li> </ol> <p>Any other possible solutions? I just feel my current setup is dirty and unstable. Thanks in advance.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload