手势之前也发过一篇,但是我感觉那个还不够轻巧。而且大多数游戏里面不会有那么复杂的手势,今天给大家分享下只有简单方向、圆形手势的代码。
virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent);
virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent);
virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent);
首先cocos2d中是通过以上三个方法判断玩家的触摸事件。 直接贴代码, 大家看后原理就知道了, 很简单。就是通过水平、垂直的运动增量判断它的运行方向。
头文件
enum GDirection //当前手势方向;
{
kGDirectionUp = 0,
kGDirectionDown,
kGDirectionLeft,
kGDirectionRight,
kGDirectionNo
};
bool b_click; //判断当前是否是单击;
bool b_debug; //调试用;
bool b_circle; //其实这个圆形的判断不是很精确;
bool cache_directionshape[4]; //方向缓存,move中用它来判断是否是单向手势
GDirection gd_direction; //手势方向;
CCPoint ccp_last,ccp_now; //记录起始、当前坐标
处理cocos2d的触摸事件
void GeometricDirection::onStarted(CCSet *pTouches, CCEvent *pEvent)
{
CCTouch *touch = (CCTouch *) pTouches->anyObject();
ccp_last = touch->locationInView(touch->view());
ccp_last = CCDirector::sharedDirector()->convertToGL(ccp_last);
b_click = true;
b_circle = false;
gd_direction = kGDirectionNo;
for (int i = 0 ; i < 4 ; i++)
{
cache_directionshape[i] = false;
}
}
void GeometricDirection::onMoved(CCSet *pTouches, CCEvent *pEvent)
{
b_click = false;
CCTouch * touch = (CCTouch*)pTouches->anyObject();
ccp_now = touch->locationInView(touch->view());
ccp_now = CCDirector::sharedDirector()->convertToGL(ccp_now);
float adsx = ccp_now.x - ccp_last.x;
float adsy = ccp_now.y - ccp_last.y;
if(abs(adsx) > abs(adsy)) //X方向增量大
{
if(adsx < 0) //左移;
cache_directionshape[0] = 1;
else
cache_directionshape[1] = 1;
}
else
{
if(adsy < 0)
cache_directionshape[2] = 1;
else
cache_directionshape[3] = 1;
}
int x = 0;
for (int i = 0 ; i< 4 ; i++)
{
if(cache_directionshape[i])
x++;
}
if(x >= 2)
b_circle = true;
}
void GeometricDirection::onEnded(CCSet *pTouches, 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(abs(adsx) > abs(adsy)) //X方向增量大
{
if(adsx < 0){
gd_direction = kGDirectionLeft;
}
else{
gd_direction = kGDirectionRight;
}
}
else
{
if(adsy < 0){
gd_direction = kGDirectionDown;
}
else{
gd_direction = kGDirectionUp;
}
}
//调试信息;
//debug();
}