cocos2dx学习之自定义你的CCSprite二监测长按和双击

http://www.xuebuyuan.com/358129.html

  上一篇我们介绍了如何给你自定义的CCSprite添加Touch监听,但是你会发现无论你点击屏幕的哪里,我们的精灵都会收到Touch事件,为什么会这样呢,主要是CCTouchDispatcher只是实现触摸事件分发,所以每一个添加到CCTouchDispatcher上的CCTouchDelegate,都是一层,屏幕大小,这也是为什么有时候我们点击到层的外面也能接受到Touch监听的原因。不管怎么说,这是我们不想看到的。其实这里cocos2dx的源代码中已经给出了解决办法,那就是CCMenu,看看它的源代码你会发现它是做了判断Touch区域的操作。我们这里也这么做。代码如下

  

boolTestSprite::isInSprite(CCTouch*theTouch){

// 返回当前触摸位置在OpenGL坐标

CCPointtouchPoint=theTouch->getLocation();

// 将世界坐标转换为当前父View的本地坐标系

CCPointreallyPoint=this->getParent()->convertToNodeSpace(touchPoint);

// 获取当前基于父view的坐标系

CCRectrect=this->boundingBox();

// CCnode->convertToNodeSpace或者 convertToWorldSpace是基于当前Node与当前Node相关

if(rect.containsPoint(reallyPoint)){

returntrue;

}

returnfalse;

}

这样子我们就能知道我们点击是不是我们的精灵了。下面我们来判断双击。代码如下

// 获取当前时间 精确到毫秒数

staticinlinelongmillisecondNow()

{

structcc_timevalnow;

CCTime::gettimeofdayCocos2d(&now,NULL);

return(now.tv_sec* 1000 + now.tv_usec/ 1000);

}

//判断是不是双击

staticinlineboolisDoubleTouch(){

staticlonglastTouchTime=0;

longthisTouchTime=millisecondNow();

if(abs(thisTouchTime-lastTouchTime)<250){

lastTouchTime=0;

returntrue;

}

else{

lastTouchTime=millisecondNow();

returnfalse;

}

}

就是简单的做一下两次点击的时间间隔,如果小于250毫米,就算做双击。单机我们给解决了,那么现在就是长按了,长安其实也是很简单就是,如果你touch的时间长于两秒,那么我们算做它长按。或不多说,上代码

voidTestSprite::checkLongPress(){

this->unschedule(schedule_selector(TestSprite::checkLongPress));

if(isInTouch&&!isInMove) {

CCLog("LONGLONG");

this->setScale(2);

this->setOpacity(200);

afterLongPress=true;

}

}

boolTestSprite::ccTouchBegan(CCTouch*pTouch,CCEvent*pEvent){

if(this->isInSprite(pTouch)) {

  isInTouch=true;

if(isDoubleTouch()) {

this->doubleClickSprite();

this->touchBeginTime=millisecondNow();

}else{

this->singleClickSprite();

this->touchBeginTime=millisecondNow();

this->schedule(schedule_selector(TestSprite::checkLongPress),2);

}

returntrue;

}

returnfalse;

}

voidTestSprite::ccTouchMoved(CCTouch*pTouch,CCEvent*pEvent) {

CCPointdeltaPoint=pTouch->getDelta();

CCLog("x=%f,y=%f",deltaPoint.x,deltaPoint.y);

if(fabs(deltaPoint.x)>1||fabs(deltaPoint.y)>1){

isInMove=true;

}

}

voidTestSprite::ccTouchEnded(CCTouch*pTouch,CCEvent*pEvent) {

isInTouch=false;

isInMove=false;

afterLongPress=false;

// 恢复精灵

this->setScale(1);

this->setPosition(orignalPoint);

this->setOpacity(255);

}

voidTestSprite::ccTouchCancelled(CCTouch*pTouch,CCEvent*pEvent){

isInTouch=false;

isInMove=false;

afterLongPress=false;

// 恢复精灵

this->setScale(1);

this->setPosition(orignalPoint);

this->setOpacity(255);

}

当然我们这里也是做了一个简单的判断,如果touch了一直没有move超过两秒我们才算做长按的。

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...