项目需要用到非常简单手势拨动,就是向上/下/左、右滑动时,界面能响应。
以下提供一个较为简单的手势滑动解决办法
GestureLayer.h
class GestureLayer: public CCLayer
{
virtual void onEnter();
virtual void onExit(); virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent);
private:
bool b_click; //判断当前是否是单击;
bool b_debug; //调试用;
bool b_circle; //其实这个圆形的判断不是很精确;
bool cache_directionshape[]; //方向缓存,move中用它来判断是否是单向手势
GDirection gd_direction; //手势方向;
CCPoint ccp_last,ccp_now; //记录起始、当前坐标
}
GestureLayer.cpp
void GestureLayer::onEnter()
{
CCLayer::onEnter();
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
}
void GestureLayer::onExit()
{
CCLayer::onExit();
CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
}
bool GestureLayer::ccTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
{
CCPoint localPoint = pTouch->getLocationInView();
ccp_last = localPoint;
ccp_last = CCDirector::sharedDirector()->convertToGL(ccp_last); localPoint = this->getParent()->convertTouchToNodeSpace(pTouch);
if (localPoint.x < || localPoint.y < )
{
return false;
}
CCSize si = getContentSize();
if (localPoint.x > si.width || localPoint.y > si.height)
{
return false;
}
b_click = true;
b_circle = false;
gd_direction = kGDirectionNo;
for (int i = ; i < ; i++)
{
cache_directionshape[i] = false;
}
return true;
}
void GestureLayer::ccTouchMoved(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
{
b_click = false;
ccp_now = pTouch->getLocationInView();
ccp_now = CCDirector::sharedDirector()->convertToGL(ccp_now);
float adsx = ccp_now.x - ccp_last.x;
float adsy = ccp_now.y - ccp_last.y;
if(fabsf(adsx) > fabsf(adsy)) //X方向增量大
{
if(adsx < )
{
//左移;
cache_directionshape[] = ;
}
else
{
cache_directionshape[] = ;
}
}
else
{
if(adsy < )
{
cache_directionshape[] = ;
}
else
{
cache_directionshape[] = ;
}
}
int x = ;
for (int i = ; i< ; i++)
{
if(cache_directionshape[i])
{
x++;
}
}
if(x >= )
{
b_circle = true;
}
}
void GestureLayer::ccTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
{
//圆形;
if(b_circle || b_click)
{
return;
}
float adsx = ccp_now.x - ccp_last.x;
float adsy = ccp_now.y - ccp_last.y;
if(fabsf(adsx) > fabsf(adsy)) //X方向增量大
{
if(adsx < )
{
gd_direction = kGDirectionLeft;
}
else
{
gd_direction = kGDirectionRight;
}
}
else
{
if(adsy < )
{
gd_direction = kGDirectionDown;
}
else
{
gd_direction = kGDirectionUp;
}
}
//判断手势类型
switch (gd_direction)
{
case kGDirectionLeft:
{
break;
}
case kGDirectionRight:
{
break;
}
default:
break;
}
}
void GestureLayer::ccTouchCancelled(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
{
ccTouchEnded(pTouch,pEvent);
}