您的位置:首页 > 移动开发 > Cocos引擎

触摸事件

2016-03-03 19:36 549 查看

一:单点触摸事件

1、分四个阶段(触摸开始、触摸移动、触摸结束、触摸取消)

2、重写以下四个函数并实现方法:

virtual bool onTouchBegan(Touch *touch, Event *unused_event);
virtual void onTouchMoved(Touch *touch, Event *unused_event);
virtual void onTouchEnded(Touch *touch, Event *unused_event);
virtual void onTouchCancelled(Touch *touch, Event *unused_event);


3、添加监听者:

auto listener=EventListenerTouchOneByOne::create();
listener->onTouchBegan=CC_CALLBACK_2(HelloWorld::onTouchBegan, this);
listener->onTouchMoved=CC_CALLBACK_2(HelloWorld::onTouchMoved, this);
listener->onTouchEnded=CC_CALLBACK_2(HelloWorld::onTouchEnded, this);
listener->onTouchCancelled=CC_CALLBACK_2(HelloWorld::onTouchCancelled, this);


4、将监听者添加到事件触摸分发器中:

Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);


5、在相应的实现方法中实现功能。

在onEnter( )函数中制定触摸优先级:

Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(listener, -128);


在onExit( )函数中释放注册

Director::getInstance()->getEventDispatcher()->removeEventListenersForTarget(this);


触摸吞噬(可以吞噬掉以后的触摸事件)

listener->setSwallowTouches(true);


二:多点触摸事件

1、首先要开启多点触摸,在ios文件夹下AppController.mm文件中找到

[eaglView setMultipleTouchEnabled:NO];


将NO改为YES

[eaglView setMultipleTouchEnabled:YES];


2、重写以下四个函数并实现方法:

virtual void onTouchesBegan(const std::vector<Touch*>& touches, Event *unused_event);
virtual void onTouchesMoved(const std::vector<Touch*>& touches, Event *unused_event);
virtual void onTouchesEnded(const std::vector<Touch*>& touches, Event *unused_event);
virtual void onTouchesCancelled(const std::vector<Touch*>&touches, Event *unused_event);


3、添加监听者:

auto listener1=EventListenerTouchAllAtOnce::create();
listener1->onTouchesBegan=CC_CALLBACK_2(HelloWorld::onTouchesBegan, this);
listener1->onTouchesMoved=CC_CALLBACK_2(HelloWorld::onTouchesMoved,this);
listener1->onTouchesEnded=CC_CALLBACK_2(HelloWorld::onTouchesEnded, this);
listener1->onTouchesCancelled=CC_CALLBACK_2(HelloWorld::onTouchesCancelled,this);


4、将监听者添加到事件触摸分发器中:

Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener1, this);


5、在相应的实现方法中实现功能。

三:单点触摸与多点触摸的区别

多点触摸默认是不开启的,需要手动开启;

多点触摸一定会接受这次触摸事件,单点触摸可以选择是否接受(根据onTouchBegan函数返回的布尔值决定);

单点触摸可以有吞噬,而多点触摸不能有吞噬;

单点触摸的优先级永远比多点触摸的高。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cocos2d-x