cocos2d-xでswipe判定実装
obejective-CのUITapGestureRecognizerが使えないので、
cocos2d-xではどうやらswipeの機能を自作しなければならないぽい。
スワイプをしたらどちらの上下左右4方向のどこにswipeしたかを知りたい。
まず、方向のenum型を用意
enum typeDirection
{
swipeUp,
swipeDown,
swipeLeft,
swipeRight,
swipeCount,
};
1フレーム前と今のフレームの位置を比較対象とする。
void GameScene::ccTouchEnded(CCTouch* pTouch, CCEvent* pEvent) { // 現在位置を取得 CCPoint currentPos = CCDirector::sharedDirector()->convertToGL(pTouch->getLocationInView()); // 1フレーム前のタッチポイントを取得 CCPoint prevPos = CCDirector::sharedDirector()->convertToGL(pTouch->getPreviousLocationInView()); float dist = ccpDistance(currentPos, prevPos); if (dist > 5.0f) { // スワイプ判定 CCPoint vec = ccpSub(currentPos, prevPos); typeDirection direction = swipeDirection(vec); CCLog("detected swipe - direction:%d",direction); } }
swipeDirection判定メソッド
// スワイプの方向を返す typeDirection GameScene::swipeDirection(CCPoint vec) { typeDirection direction; float angle = ccpToAngle(vec)*180/M_PI; if(45.0f <= angle && angle < 135.0f) //up { direction = swipeUp; } else if(-135.0f <= angle && angle < -45.0f) //down { direction = swipeDown; } else if((135.0f <= angle && angle < 180.0f) || (-180.0f <= angle && angle < -135.0f)) //left { direction = swipeLeft; } else if((0 <= angle && angle < 45.0f) || (-45.0f <= angle && angle < 0) ) //right { direction = swipeRight; } return direction; }
試してみると、シビアに判定されるので、違う方法の実装を今後考えたい。
下記を見つけたのでこれできれいなswipe実装できるかな。
https://github.com/spalx/cocos2d-x-extensions