yag Site Admin
註冊時間: 2007-05-02 文章: 689
2704.11 果凍幣
|
發表於: 2012-10-20, AM 12:57 星期六 文章主題: [cocos2d-x]CCLayer子類別中拖動CCSprite的方法 |
|
|
假設有個HelloWorld類別是CCLayer的子類別
於HelloWorld.h檔中加入:
代碼: | virtual void onEnter();
virtual void onExit();
bool containsTouchLocation(CCTouch *pTouch);
virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);
CCSprite *mSprite;
CCPoint mTouchPoint; |
於HelloWorld.cpp檔中加入:
代碼: | void HelloWorld::onEnter()
{
CCDirector* pDirector = CCDirector::sharedDirector();
pDirector->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
CCLayer::onEnter();
}
void HelloWorld::onExit()
{
CCDirector* pDirector = CCDirector::sharedDirector();
pDirector->getTouchDispatcher()->removeDelegate(this);
CCLayer::onExit();
}
bool HelloWorld::containsTouchLocation(CCTouch *pTouch)
{
return mSprite->boundingBox().containsPoint(pTouch->getLocation());
}
bool HelloWorld::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
if ( !containsTouchLocation(pTouch) ) return false;
mTouchPoint = pTouch->getLocation();
return true;
}
void HelloWorld::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
CCPoint touchPoint = pTouch->getLocation();
touchPoint = ccpSub(touchPoint, mTouchPoint);
touchPoint = ccpAdd(mSprite->getPosition(), touchPoint);
mSprite->setPosition( touchPoint );
mTouchPoint = pTouch->getLocation();
} |
其中mSprite在HelloWorld的init中已初始化建立 |
|