我们这个Demo的效果就是可以拖动CCLayer上的特定的一个精灵.这应该是一个很常见的效果.
一、我们直接在COCOS2D-X自带的HelloCpp的工程中添加代码即可.我们在初始化中添加如下代码:
setTouchEnabled(true);//开启触屏响应
CCSize szWin = CCDirector::sharedDirector()->getVisibleSize();
CCPoint ptCenterOfLayer = CCPointMake(szWin.width/2,szWin.height/2);
CCSprite* pShoose = CCSprite::create("shoose.jpg");
pShoose->setPosition(ptCenterOfLayer);
this->addChild(pShoose,0,1000);//添加需要拖动的精灵结点
二、我们需要重写下面三个函数:
void HelloWorld::registerWithTouchDispatcher()
{
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0,true);
}
bool HelloWorld::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
CCPoint ptClick = pTouch->getLocation();
CCNode *pNode = this->getChildByTag(1000);//SSPrite* pSpr = static_cast<CCSprite *>(this->getChildByTag(1000));
return pNode->boundingBox().containsPoint(ptClick);//OR pNode->boundingBox().containsPoint(this->convertTouchToNodeSpace(pTouch));判断精灵是否被点击
}
void HelloWorld::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
CCPoint Diff = pTouch->getDelta();
CCNode *pNode = this->getChildByTag(1000);
CCPoint ptCurrent = pNode->getPosition();
pNode->setPosition(ccpAdd(ptCurrent,Diff));
}
三、在运行上面的程序的时候我们会发现一个问题就是我们会把精灵的部分拖动到屏幕之外.这可能是我们不想要的.所以还需要加入判断.代码如下:
void HelloWorld::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
CCPoint Diff = pTouch->getDelta();
CCNode *pNode = this->getChildByTag(1000);
CCPoint ptCurrent = pNode->getPosition();
pNode->setPosition(ccpAdd(ptCurrent,Diff));
CCRect reRect = pNode->boundingBox();
/************************以下是新添加的代码************************/
CCSize szWin = CCDirector::sharedDirector()->getWinSize();
CCPoint ptLowerLeft = CCPointMake(reRect.origin.x,reRect.origin.y);
CCPoint DeltaOfLowerLeft;
DeltaOfLowerLeft.x = min(max(reRect.origin.x,0),szWin.width-reRect.size.width) - ptLowerLeft.x;
DeltaOfLowerLeft.y = min(max(reRect.origin.y,0),szWin.height-reRect.size.height)- ptLowerLeft.y;
pNode->setPosition(ccpAdd(pNode->getPosition(),DeltaOfLowerLeft));//锚点移动的"差距"和左下角的是一样的
}
PS:因为是基础学习,故不作过多分析.后继会有更多精彩内容,敬请大家关注