2012-06-14 78 views
2

我試圖將動畫從cocos2d轉換爲cocos2d-x,但無濟於事。我沒有收到任何明顯的錯誤消息,只是它發生在倒數第二行。Cocos2d-x動畫錯誤

CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("swim_male.plist"); 
CCSpriteBatchNode *sceneSpriteBatchNode = CCSpriteBatchNode::batchNodeWithFile("swim_male.png"); 

this->addChild(sceneSpriteBatchNode); 

CCAnimation* animation = CCAnimation::animation(); 
animation->setDelayPerUnit(.05f);  
char* fn = new char; 

for (int i = 1; i <= 10; i++) { 
    sprintf(fn, "character_Male00%02d.png", i); 
    CCSpriteFrame* pFrame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(fn); 
    animation->addSpriteFrame(pFrame); 
} 

CCSprite *spriteAnim = CCSprite::spriteWithSpriteFrameName("character_Male0001.png"); 
spriteAnim->setPosition(ccp(100, 200)); 
CCAnimate *animate = CCAnimate::actionWithAnimation(animation); 
CCAction *act = CCRepeatForever::actionWithAction(animate); 
spriteAnim->runAction(act); 

sceneSpriteBatchNode->addChild(spriteAnim, 2); 
+0

什麼錯誤消息的文本? – Morion

+0

EXEC_BAD_ACCESS – user1235155

+0

這意味着其中一個變量是NULL。檢查調試器,什麼變量是NULL並導致崩潰 – Morion

回答

4

您正在爲sprintf分配單個字符。然後sprintf將字符串寫入fn指向的內存之外,因爲它長於1個字符。

代替

char* fn = new char; 

for (int i = 1; i <= 10; i++) { 
    sprintf(fn, "character_Male00%02d.png", i); 
    CCSpriteFrame* pFrame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(fn); 
    animation->addSpriteFrame(pFrame); 
} 

爲此

char fn[128]; 

for (int i = 1; i <= 10; i++) { 
    sprintf(fn, "character_Male00%02d.png", i); 
    CCSpriteFrame* pFrame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(fn); 
    animation->addSpriteFrame(pFrame); 
} 
+0

這就是我正在尋找的。謝謝。 – user1235155

4

使用C++,

char* fn = new char --> bad; 
char* fn = new char[128]; 

... 

delete []fn; 
0

字符* FN =新字符;沒有指定分配給fn的大小。

你應該寫這樣

for (int i = 1; i <= 10; i++) 
    { 
    char* fn = new char[strlen("character_Male0002d.png")+sizeof(i)+1]; 
    sprintf(fn, "character_Male00%02d.png", i); 
    CCSpriteFrame* pFrame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(fn); 
     animation->addSpriteFrame(pFrame); 
    delete fn; 
    fn = NULL ; 
    } 
1

您可以直接這樣

CCSpriteBatchNode* spritebatch = CCSpriteBatchNode::create("horse.png"); 
CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache(); 
cache->addSpriteFramesWithFile("horse.plist"); 

hero = CCSprite::createWithSpriteFrameName("horse_1.png"); 
addChild(spritebatch); 
spritebatch->addChild(hero); 

CCArray* animFrames = CCArray::createWithCapacity(16); 
char str[100] = {0}; 
for(int i = 1; i < 16; i++) 
{ 
    sprintf(str, "horse_%i.png", i); 
    CCSpriteFrame* frame = cache->spriteFrameByName(str); 
    animFrames->addObject(frame); 
} 
CCAnimation* animation = CCAnimation::createWithSpriteFrames(animFrames, .1f); 
animation->setRestoreOriginalFrame(true); 
hero->runAction(CCRepeatForever::create(CCAnimate::create(animation)));