2014-02-19 42 views
0

在使用cocos2d-x中的CCArray时遇到问题。 我在init()函数的顶部声明了CCArray * arrCs,我为arrCs设置了值,但是在touch事件中从它获得值之后,它什么也没有。 请帮助我,谢谢大家。C++无法获取cocos2d-x中全局变量的值

在MainGame.cpp

int radius= 32; 
float scaleImage= 0.5; 
int nItem= 60; 
float pMargin= 5; 

int limitTime= 70; 
float timeWaiting= 8; 
bool opTouch= true; 
int lastIndex= -1; 
Size visibleSize; 

CCArray *arrCs; 

bool MainGame::init(){ 
    arrCs= CCArray::create(); 

    int xx= pMargin+ radius; 
    int yy= pMargin+ radius; 

    int inLabel= 0; 
    for (int i=0; i<nItem; i++) { 
     inLabel= i; 
     if (i>((nItem/2)-1)) { 
      inLabel= i-(nItem/2); 
     } 

     CCString *iconName= CCString::createWithFormat("ricon_%i.png", inLabel); 
     Sprite *cs= CCSprite::create(iconName->getCString()); 
     cs->setPosition(Point(xx, yy)); 
     cs->setTag(-1); 
     cs->setScale(scaleImage);  

/*****SET VALUE FOR arrCs ******************/ 
     arrCs->addObject(cs); 

     this->addChild(cs, (1+ rand()%3)); 

     xx= xx+ (radius*2)+ pMargin; 
     if (xx+ (radius/2)> visibleSize.width) { 
      xx= radius + pMargin; 
      yy= yy+(radius*2)+ pMargin; 
     } 
    } 
} 




void MainGame::onTouchesEnded(const std::vector<Touch*>& touches, Event* event){ 
/******** arrCs has nothing ************/ 
     for (int i=0; i< arrCs->count(); i++) { 
     } 
} 

回答

2

CCArray是一个自动释放物体(参见创建方法),并且在离开init方法时被破坏。请在你的init方法中调用你的数组中的retain(arrCs-> retain()),并且你应该在onTouchesEnded中得到预期的结果。

Regards,Laurent