【玩转cocos2d-x之十八】仿《中国好学霸》文字拖拽和定位
现在各种猜成语猜歌名好学霸之类的游戏火的一塌糊涂。本节就介绍下文字的拖拽和定位。
基本原理
其实这只是精灵的简单拖拽和坐标的识别而已。当触摸点在精灵的范围内,精灵可以感应拖动,当触摸结束进行位置判断,如果在有效范围内就进行自动定位。
实现
背景加入和文字精灵的加入
这里是采用这一节所述方式添加中文。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| 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* 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; }
|
触摸的实现和拖拽的定位
因为3.0版本cocos2d-x的触摸实现已经变更了,所以这里不再赘述,3.0之前的触摸的原理和实现具体可以参见这一节。
注册触摸事件
1 2 3 4 5
| void AutoSet::registerWithTouchDispatcher(void) { CCDirector *pDirector=CCDirector::sharedDirector(); pDirector->getTouchDispatcher()->addTargetedDelegate(this,0,true); }
|
触摸开始
1 2 3 4
| bool AutoSet::ccTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent) { return true; }
|
触摸过程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 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); CCPoint toPoint=ccpAdd(text->getPosition(),offSet); text->setPosition(toPoint); } }
|
触摸结束
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 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); }
|
效果图
源码下载
源码下载