使用代碼訪問Cocos Studio場景編輯器中的CCSprite相關屬性

  問題1

  

如題的問題有許多人問,其實TestCPP這個Demo中已經有明確說明(但似乎又不太明確?!)。


  示例函數見SceneEditorTest.cpp文件中的cocos2d::CCNode* SpriteComponentTest::createGameScene()處提供的如下代碼:


   

CCNode *pNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile("scenetest/SpriteComponentTest/SpriteComponentTest.json");
    if (pNode == NULL)
    {
        return NULL;
    }
    CCActionInterval*  action1 = CCBlink::create(2, 10);
    CCActionInterval*  action2 = CCBlink::create(2, 5);
    CCComRender *pSister1 = static_cast<CCComRender*>(pNode->getChildByTag(10003)->getComponent("CCSprite"));
    pSister1->getNode()->runAction(action1);

  

  問題

  

  請注意,上面的解析好像繞了一個彎,使用如下代碼如何呢?

pNode->getChildByTag(10003)->runAction(action1);

答案是肯定不行!


  類似的例子還有:

WIDTHOFPLACEHOLDER =m_pCurNode->getChildByTag(10006)->getContentSize().width;

  也是不行的,只能替換成如下方式:

   

CCComRender *pPlaceholder10006 = static_cast<CCComRender*>(m_pCurNode->getChildByTag(10006)->getComponent("CCSprite"));
WIDTHOFPLACEHOLDER =pPlaceholder10006->getNode()->getContentSize().width;//width of placeholder

  不能只瞭解getChildByTag()也返回一個CCNode*,就直接使用上面表達。

  

  問題

  

  通過上面代碼,可以(而且必須這樣)訪問到精靈組件的大小等數據,但是如果定位組件位置就不行了。例如下面:
  

CCPoint point=pPlaceholder10006->getNode()->getPosition();

這樣得到的座標只是一個(0,0)!!!

  正確的方法應該是:使用如下方法:

  

CCPoint point=m_pCurNode->getChildByTag(10006)->getPosition();


  淺析


  具體原因,自然與場景編輯器的設計及後臺解析器有關。儘管表面看上去繞了一個彎才引用到了相應精靈結點(及操作相應屬性)。但是,這樣的設計(當然包括前面兩者)卻具備了極大的靈活性:把CCNode與CCComponent(CCComRender類的父類)有機地結合到一起,從而纔會實現在場景編輯器設計的場景中靈活引用UI編輯器設計內容,並通過後臺代碼進行靈活控制。也就是,使CCNode與CCComponent最終實現了統一操作目的。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章