您的位置:首页 >> Cocos2d-x >> 和屌丝一起学cocos2dx-触屏事件

和屌丝一起学cocos2dx-触屏事件

[ 孤狼 | 2015-02-09 17:22:01 | Cocos2d-x | 2479°C | 0条评论 ]
声 明

本教程仅用于初学cocos2dx同学使用,内容由本人(孤狼)学习过程中笔记编写,本教程使用cocos2dx版本为2.1.4。本教程内容可以自由转载,但必须同时附带本声明,或注明出处。
gl.paea.cn版权所有。


       Hello,大家好,欢迎回到“和屌丝一起学cocos2dx”系列教程,上节,我们说到了“33种场景切换”,不知道大家回去试了没有呢,是不是也做出来效果了呢?这节我们说一下触屏事件。


【一】:为毛学他


       Fuck,你说为啥,上节你就开始闹情绪。


【二】:函数


addTargeteDelegate("触屏事件委托CCTouchDelegate目标","优先级","是否拦截触屏事件");


触屏事件:

1.当用户第一次触碰手机屏幕时响应的回调函数

virtual bool ccTouchBegan(CCTouch * touch,CCEvent * event);

2.当用户手指在手机屏幕上滑动时响应的回调函数

virtual void ccTouchMoved(CCTouch * touch,CCEvent * event);

3.当用户手指在离开手机屏幕上时响应的回调函数

virtual void ccTouchEnded(CCTouch * touch,CCEvent * event);


流程:(感谢 袁辉、春丽、Rock You 技术支持)

       当用户碰到屏幕就调用ccTouchBegan,用户若是滑动则开始不停的回调ccTouchMoved(类似更新),当用户离开屏幕调用ccTouchEnded。


【三】:问题


       昨天我们说了onEnter、onExit,但是今天我在调用的时候却无法执行action动作,最后在onEnter、onExit函数里,继承一下父类就实现了,这里要用父类初始化下,所以CCLayer::onEnter();这样的初始化,一定不能忘了写。(感谢 秋风、蒙大齐 技术支持)


【四】:示例


1.新建项目Touchdemo

2.载入一张图作为资源



Touchdemo.h


1.写上触屏事件和生命周期

//触屏事件

virtual bool ccTouchBegan(CCTouch * touch,CCEvent * event);

virtual void ccTouchMoved(CCTouch * touch,CCEvent * event);

virtual void ccTouchEnded(CCTouch * touch,CCEvent * event);

//生命周期

virtual void onEnter();

virtual void onExit();



Touchdemo.cpp


1.在初始化函数里面添加一个sp对象和ttf对象

//-new-//

CCSize mysize=CCDirector::sharedDirector()->getWinSize();

CCSprite* pSprite = CCSprite::create("cat.png");

pSprite->setPosition(ccp(mysize.width/2, mysize.height/2));

this->addChild(pSprite,0,1);

CCLabelTTF * ttf=CCLabelTTF::create("none","Thonburi",24);

ttf->setPosition(ccp(mysize.width/2,mysize.height-50));

this->addChild(ttf,1,2);

//-new-//



2.实现触屏事件

bool Touchdemo::ccTouchBegan(CCTouch * ctouch,CCEvent * event){

CCLabelTTF * ttf=(CCLabelTTF *)this->getChildByTag(2);

ttf->setString("in");

return true;

}

void Touchdemo::ccTouchMoved(CCTouch * ctouch,CCEvent * event){

CCLabelTTF * ttf=(CCLabelTTF *)this->getChildByTag(2);

ttf->setString("move");

CCPoint point=ctouch->getLocation();

CCSprite * sp=(CCSprite *)this->getChildByTag(1);

sp->setPosition(point);

}

void Touchdemo::ccTouchEnded(CCTouch * ctouch,CCEvent * event){

CCSize mysize=CCDirector::sharedDirector()->getWinSize();

CCLabelTTF * ttf=(CCLabelTTF *)this->getChildByTag(2);

ttf->setString("out");

CCSprite * sp=(CCSprite *)this->getChildByTag(1);

CCActionInterval * a1=CCMoveTo::create(5.0f,ccp(mysize.width/2,mysize.height/2));

sp->runAction(a1);

}



3.实现生命函数

void Touchdemo::onEnter(){

//开启触屏监听

CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0,false);

CCLayer::onEnter();//一定不要忘了

}

void Touchdemo::onExit(){

//关闭触屏监听

CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);

CCLayer::onExit();//一定不要忘了

}



       最后我们来看一下效果:



本节DEMO下载


转载请注明出处:http://gl.paea.cn/n.php?n=27
 
如您看得高兴,欢迎随意投喂,让我们坚持创作!
赞赏一个鸡腿
还没有人留下遗迹
综合 · 搜索