其实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五个函数 只是在触摸函数中 判断的不再是两个触摸点 而是三个或者四个触摸点 然后在触摸移动函数中改变某些节点属性
实际实现这个功能的时候 需要在触摸开始函数中和触摸移动的函数中 判断这三个或者四个的触摸点之间的距离 还有这三个或者四个触摸点是否移动的方向大概是否是平行的等细节 其实我们可以抽象出一个单点触摸管道 反应一个触摸点的运动轨迹 这样不管是三个还是四个触摸点 只要检测数量和触摸轨迹是否相似就可以