原創作品,轉載請標明:http://blog.csdn.net/jackystudio/article/details/13287519
現在各種猜成語猜歌名好學霸之類的遊戲火的一塌糊塗。本節就介紹下文字的拖拽和定位。
1.基本原理
其實這只是精靈的簡單拖拽和座標的識別而已。當觸摸點在精靈的範圍內,精靈可以感應拖動,當觸摸結束進行位置判斷,如果在有效範圍內就進行自動定位。
2.實現
2.1.背景加入和文字精靈的加入
這裏是採用這一節http://blog.csdn.net/jackystudio/article/details/13014883所述方式添加中文。
bool AutoSet::init()
{
bool bRet=false;
do
{
CC_BREAK_IF(!CCLayer::init());
CCSize visiableSize=CCDirector::sharedDirector()->getVisibleSize();
CCSprite* background=CCSprite::create("AutoSetBk.jpg");
background->setPosition(ccp(visiableSize.width/2,visiableSize.height/2));
this->addChild(background);//添加背景
//利用CCDictionary來讀取xml
CCDictionary* chnStrings = CCDictionary::createWithContentsOfFile("CHN_Strings.xml");
const char *hao = ((CCString*)chnStrings->objectForKey("hao"))->m_sString.c_str();
text=CCLabelTTF::create(hao,"Arial",50);
text->setPosition(ccp(120,160));
text->setColor(ccc3(0,0,0));
this->addChild(text);//添加文本
this->setTouchEnabled(true);//設置觸摸可用
bRet=true;
} while (0);
return bRet;
}
2.2.觸摸的實現和拖拽的定位
因爲3.0版本cocos2d-x的觸摸實現已經變更了,所以這裏不再贅述,3.0之前的觸摸的原理和實現具體可以參見這一節http://blog.csdn.net/jackystudio/article/details/11860007
2.2.1註冊觸摸事件
void AutoSet::registerWithTouchDispatcher(void)
{
CCDirector *pDirector=CCDirector::sharedDirector();
pDirector->getTouchDispatcher()->addTargetedDelegate(this,0,true);//單點觸摸
}
2.2.2.觸摸開始
bool AutoSet::ccTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
{
return true;//返回true表示接收觸摸事件
}
2.2.3.觸摸過程
void AutoSet::ccTouchMoved(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
{
CCPoint beginPoint = pTouch->getLocationInView(); //獲取觸摸位置
beginPoint = CCDirector::sharedDirector()->convertToGL(beginPoint);//座標轉換
CCPoint pt=text->getPosition();
CCRect rect=CCRectMake(pt.x-30,pt.y-30,60,60);
if (rect.containsPoint(beginPoint))//判斷觸摸點是否在文字上
{
CCPoint endPoint=pTouch->getPreviousLocationInView();//獲取觸摸的前一個位置
endPoint=CCDirector::sharedDirector()->convertToGL(endPoint);
CCPoint offSet =ccpSub(beginPoint,endPoint);//獲取offset
CCPoint toPoint=ccpAdd(text->getPosition(),offSet); //獲取真正移動位置
text->setPosition(toPoint);//移動文字
}
}
2.2.4.觸摸結束
void AutoSet::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
CCPoint lastPoint = pTouch->getLocationInView();//獲取觸摸結束點位置
lastPoint = CCDirector::sharedDirector()->convertToGL(lastPoint);
CCRect rect=CCRectMake(330,130,60,60);
CCMoveTo* moveto;
if (!rect.containsPoint(lastPoint))//如果未在指定區域,還原到初始位置
{
moveto=CCMoveTo::create(0.1f,ccp(120,160));
}
else//如果在指定區域,移動到該區域中心
{
moveto=CCMoveTo::create(0.1f,ccp(360,160));
}
text->runAction(moveto);
}