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

cocos2d-x基础学习--添加触摸事件

2014-12-17 22:21 295 查看
         使用cocos2d来开发手机游戏,为我们的游戏添加触摸事件是游戏交互必须的,使用cocos2d-x,添加触摸事件也十分简单。、触摸事件分为单点触摸和多点触摸。

         1,添加单点触摸事件,表示单点触摸事件的类为EventListenerTouchOneByOne。首先调用create方法创建出一个指针对象,然后用闭包函数的形式向该对象传递有关触摸的函数。有关触摸的函数主要有四个:

             1)onTouchBegan:触摸按下时被响应,当返回false时之后的触摸事件不会被响应。

             2)onTouchMoved:触摸移动时被响应。

             3)onTouchEnded:触摸抬起时被响应。

             4)onTouchCancelled:触摸事件取消时被响应。

          我们可以在触摸事件中获取触摸点,在判断我们的精灵类或控件是否包含该触摸点,从而做出响应。 auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = [a](Touch *t, Event *e){
if (a->getTextureRect().containsPoint(t->getLocation()))
{
log("onTouchBegan");
}
return true;
};
listener->onTouchMoved = [a](Touch *t, Event *e){
if (a->getTextureRect().containsPoint(t->getLocation()))
{
log("onTouchMoved");
}
};
listener->onTouchEnded = [a](Touch *t, Event *e){
if (a->getTextureRect().containsPoint(t->getLocation()))
{
log("onTouchEnded");
}
};
listener->onTouchCancelled = [a](Touch *t, Event *e){
if (a->getTextureRect().containsPoint(t->getLocation()))
{
log("onTouchCancelled");
}
};          接下来我们将触摸事件添加进来
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);
          第二个参数表示该触摸事件被添加到哪个对象中,在此我直接将该触摸事件添加到我们布景层Layer类中。
        2,添加多点触摸事件,方法与添加单点触摸事件类似,多点触摸的类是EventListenerTouchAllAtOnce。当我们添加了多点触摸事件时,单点触摸事件将不再被响应。 auto listeners = EventListenerTouchAllAtOnce::create();
listeners->onTouchesBegan = [](std::vector<Touch *> ts, Event *e){
log("onTouchesBegan");
};
listeners->onTouchesMoved = [](std::vector<Touch *> ts, Event *e){
log("onTouchesMoved");
};
listeners->onTouchesEnded = [](std::vector<Touch *> ts, Event *e){
log("onTouchesEnded");
};
listeners->onTouchesCancelled = [](std::vector<Touch *> ts, Event *e){
log("onTouchesCancelled");
};
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listeners, this);           我们可以在vector中得到所有的触摸点,并作出相应处理。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息