2013-07-16 29 views
0

爲什麼在cocos2dx中拖動一個精靈非常困難!這樣做在我的touchesBegan方法讓一個精靈出現在觸摸的地方並將其拖拽到

void HelloWorld::ccTouchesBegan(cocos2d::CCSet* touches, cocos2d::CCEvent* event){ 
    CCSprite *splash = CCSprite::spriteWithFile("splash3.png"); 
    CCTouch* pTouch = (CCTouch*)(touches->anyObject()); 
    CCPoint location = pTouch->locationInView(); 
    location = CCDirector::sharedDirector()->convertToGL(location); 
    splash->setPosition(ccp(location.x,location.y)); 
    this->addChild(splash,5); 
} 


void HelloWorld::ccTouchesMoved(cocos2d::CCSet* touches, cocos2d::CCEvent* event){ 
    CCSprite *splash = CCSprite::spriteWithFile("splash3.png"); 
    CCTouch* pTouch = (CCTouch*)(touches->anyObject()); 
    CCPoint location = pTouch->locationInView(); 
    location = CCDirector::sharedDirector()->convertToGL(location); 
    splash->setPosition(ccp(location.x,location.y)); 
    this->addChild(splash,5); 
} 

我究竟做錯了什麼,並更多的工作要做?並有一個更簡單的方法來做到這一點?

回答

0

您只需要添加一個精靈一次。您可以保留全局引用或使用其標記檢索精靈。此外,您可能會錯誤地計算觸摸位置。試試這個

void HelloWorld::ccTouchesBegan(cocos2d::CCSet* touches, cocos2d::CCEvent* event){ 
    CCSprite *splash = CCSprite::spriteWithFile("splash3.png"); 
    CCPoint location = getPositionFromTouches(touches, event); 
    splash->setPosition(ccp(location.x,location.y)); 
    this->addChild(splash,5, 100); 
} 


void HelloWorld::ccTouchesMoved(cocos2d::CCSet* touches, cocos2d::CCEvent* event){ 
    CCSprite *splash = (CCSprite*) getChildByTag(100); 
    CCPoint location = getPositionFromTouches(touches, event); 
    splash->setPosition(ccp(location.x,location.y)); 
} 

CCPoint HelloWorld::getPositionFromTouches(CCSet* _touches, CCEvent* event) { 

    CCArray *allTouches = CCArray::create(); 

    CCSetIterator it; 

    for(it = _touches->begin(); it != _touches->end(); it++) 
    { 
     allTouches->addObject((CCTouch *)*it); 
    } 
    //CCArray *allTouches = getAllTouchesFromSet(_touches); 

    CCTouch* fingerOne = (CCTouch *)allTouches->objectAtIndex(0); 
    CCPoint pointOne = CCDirector::sharedDirector()->convertToUI(fingerOne->getLocationInView()); 

    CCPoint location = _armadilloSingleton->convertToNodeSpace(pointOne); 
    return location; 
} 
-1

spriteWithFile是不存在的cocos2d2.0.4
那麼請你根據最新版本更新代碼COCOCS2D