其實cocos2d-x的多點觸摸事件可以實作很多功能:譬如縮放 和簡單的手勢識别
在windows7 或者在OS X平台中暫時還不支援多點觸控 請将項目部署到windows8,ios,或者安卓平台中
既然用到多點觸控 不管什麼功能 肯定要在初始化函數中 設定SetTouchEnable(true) 之後便是重載registerWithTouchDispatcher等五個函數
實作縮放功能:
void HelloWorld::registerWithTouchDispatcher(void)
{
CCDirector::sharedDirector()->getTouchDispatcher()->addStandardDelegate(this, 0);
}
void HelloWorld::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent)
{
if(pTouches->count() >= 2){
CCSetIterator iter = pTouches->begin();
CCPoint mPoint1 = ((CCTouch*)(*iter))->locationInView();
mPoint1 = CCDirector::sharedDirector()->convertToGL(mPoint1);
iter ++;
CCPoint mPoint2 = ((CCTouch*)(*iter))->locationInView();
mPoint2 = CCDirector::sharedDirector()->convertToGL(mPoint2);
distance = sqrt((mPoint1.x - mPoint2.x) * (mPoint1.x - mPoint2.x) + (mPoint1.y - mPoint2.y) * (mPoint1.y - mPoint2.y));
deltax = (mPoint1.x + mPoint2.x)/2 - pSprite->getPositionX();
deltay = (mPoint1.y + mPoint2.y)/2 - pSprite->getPositionY();
}
}
void HelloWorld::ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent)
{
if(pTouches->count() >= 2){
CCSetIterator iter = pTouches->begin();
CCPoint mPoint1 = ((CCTouch*)(*iter))->locationInView();
mPoint1 = CCDirector::sharedDirector()->convertToGL(mPoint1);
iter ++;
CCPoint mPoint2 = ((CCTouch*)(*iter))->locationInView();
mPoint2 = CCDirector::sharedDirector()->convertToGL(mPoint2);
float mdistance = sqrt((mPoint1.x - mPoint2.x) * (mPoint1.x - mPoint2.x) + (mPoint1.y - mPoint2.y) * (mPoint1.y - mPoint2.y));
mscale = mdistance / distance * mscale;
distance = mdistance;
pSprite->setScale(mscale);
float x = (mPoint1.x + mPoint2.x)/2 - deltax;
float y = (mPoint1.y + mPoint2.y)/2 - deltax;
pSprite->setPosition(ccp(x,y));
deltax = (mPoint1.x + mPoint2.x)/2 - pSprite->getPositionX();
deltay = (mPoint1.y + mPoint2.y)/2 - pSprite->getPositionY();
}
}
void HelloWorld::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent)
{
}
void HelloWorld::ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent)
{
}
Summayr:實作縮放的邏輯 就是再觸摸函數中 判斷是是否是大于兩個 如果是取前面兩個 計算出兩點之間的距離 再在觸摸移動函數中 繼續監測觸摸點是否大于兩個 如果是計算再計算出兩個點之間的距離 然後得到縮放比例 然後調用setScale設定縮放比例
ps:在蘋果電腦中的iphone模拟器中可以使用Option鍵加滑鼠模拟兩點觸摸來測試
遊戲識别簡單的手勢:
現在移動終端很多隻含有一個觸摸屏 這就意味缺少必要的按鍵幫助使用者簡便的操作 這時候就需要遊戲識别簡單的手勢 比如:在螢幕中有三個或者四個手指在螢幕上滑動就會更改一些界面或者節點的屬性 其實就是上面縮放功能的一個發散 同樣是在觸摸開始函數中setTouchEnable(true) 然後重載registerWithTouchDispatcher五個函數 隻是在觸摸函數中 判斷的不再是兩個觸摸點 而是三個或者四個觸摸點 然後在觸摸移動函數中改變某些節點屬性
實際實作這個功能的時候 需要在觸摸開始函數中和觸摸移動的函數中 判斷這三個或者四個的觸摸點之間的距離 還有這三個或者四個觸摸點是否移動的方向大概是否是平行的等細節 其實我們可以抽象出一個單點觸摸管道 反應一個觸摸點的運動軌迹 這樣不管是三個還是四個觸摸點 隻要檢測數量和觸摸軌迹是否相似就可以