Cocos2d-x3.0 触摸事件

TouchableSpriteTest

auto winSize = Director::getInstance()->getWinSize();

    Point origin = Director::getInstance()->getVisibleOrigin();

    auto containerForSprite1 = Node::create();
    auto sprite1 = Sprite::create("CyanSquare.png");
    sprite1->setPosition(origin + Point(winSize.width / 2, winSize.height / 2) + Point(-80, 80));
    containerForSprite1->addChild(sprite1);
    addChild(containerForSprite1,10);

    auto sprite2 = Sprite::create("MagentaSquare.png");
    sprite2->setPosition(origin + Point(winSize.width / 2, winSize.height / 2));
    addChild(sprite2,20);

    auto sprite3 = Sprite::create("YellowSquare.png");
    sprite3->setPosition(Point(0, 0));
    sprite2->addChild(sprite3, 1);

    auto listener1 = EventListenerTouchOneByOne::create();
    listener1->setSwallowTouches(true);

    listener1->onTouchBegan = [](Touch* touch,Event* event){
        auto target = static_cast<Sprite*>(event->getCurrentTarget());

        Point locationInNode = target->convertToNodeSpace(touch->getLocation());
        Size s = target->getContentSize();
        Rect rect = Rect(0, 0, s.width, s.height);
        if (rect.containsPoint(locationInNode)) {
            log("sprite began... x = %f, y = %f",locationInNode.x , locationInNode.y);
            target->setOpacity(180);
            return true;
        }
        return false;
    };

    listener1->onTouchMoved = [](Touch* touch,Event* event){

        auto target = static_cast<Sprite*>(event->getCurrentTarget());
        target->setPosition(target->getPosition() + touch->getDelta());

    };

    listener1->onTouchEnded = [=](Touch* touch,Event* event){

        auto target = static_cast<Sprite*>(event->getCurrentTarget());
        log("sprite onTouchedEnded");

        target->setOpacity(255);
        if (target == sprite2) {
            containerForSprite1->setLocalZOrder(100);

        }
        else if (target == sprite1)
        {
            containerForSprite1->setLocalZOrder(0);
        }
    };

    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, sprite1);
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1->clone(), sprite2);
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1->clone(), sprite3);

    auto removeAllTouchItem = MenuItemFont::create("Remove All Touch Listeners", [this](Ref* sender){

        auto senderItem = static_cast<MenuItemFont*>(sender);
        senderItem->setString("Only Next item could be clicked");

        _eventDispatcher->removeEventListenersForType(EventListener::Type::TOUCH_ONE_BY_ONE);

        auto nextItem = MenuItemFont::create("Next", [=](Ref* sender){

        });

    });

    removeAllTouchItem->setFontSizeObj(16);
    removeAllTouchItem->setPosition(Point(100, 50));

    auto menu = Menu::create(removeAllTouchItem, NULL);
    menu->setPosition(Point(0, 0));
    menu->setAnchorPoint(Point(0, 0));
    addChild(menu);

效果:

CustomEventTest

Point origin = Director::getInstance()->getVisibleOrigin();
    Size size = Director::getInstance()->getVisibleSize();

    MenuItemFont::setFontSize(20);

    auto statusLabel = Label::createWithSystemFont("No custom event 1 received!", "", 20);
    statusLabel->setPosition(origin + Point(size.width/2, size.height-90));
    addChild(statusLabel);

    _listener = EventListenerCustom::create("game_custom_event1", [=](EventCustom* event){
        std::string str("Custom event 1 received, ");
        char* buf = static_cast<char*>(event->getUserData());
        str += buf;
        str += " times";
        statusLabel->setString(str.c_str());
    });

    _eventDispatcher->addEventListenerWithFixedPriority(_listener, 1);

    auto sendItem = MenuItemFont::create("Send Custom Event 1", [=](Ref* sender){
        static int count = 0;
        ++count;

        char* buf = new  char[10];
        sprintf(buf, "%d",count);
        EventCustom event("game_custom_event1");
        event.setUserData(buf);
        _eventDispatcher->dispatchEvent(&event);
        CC_SAFE_DELETE_ARRAY(buf);

    });
    sendItem->setPosition(origin + Point(size.width / 2, size.height / 2));

    auto menu = Menu::create(sendItem, NULL);
    menu->setPosition(Point(0, 0));
    menu->setAnchorPoint(Point(0, 0));
    addChild(menu , -1);

RemoveAndRetainNodeTest

    Point origin = Director::getInstance()->getVisibleOrigin();
    Size size = Director::getInstance()->getVisibleSize();

     _sprite = Sprite::create("CyanSquare.png");
    _sprite->setPosition(origin+Point(size.width/2, size.height/2));
    addChild(_sprite, 10);

    // Make sprite1 touchable
    auto listener1 = EventListenerTouchOneByOne::create();
    listener1->setSwallowTouches(true);
    listener1->onTouchBegan = [](Touch* touch ,Event* event){

        auto target = static_cast<Sprite*>(event->getCurrentTarget());
        Point locationInNode = target->convertToNodeSpace(touch->getLocation());
        Size s = target->getContentSize();
        Rect rect = Rect(0, 0, s.width, s.height);

        if (rect.containsPoint(locationInNode)) {
            log("sprite began... x = %f, y = %f",locationInNode.x,locationInNode.y);
            target->setOpacity(180);
            return true;
        }
        return false;

    };

    listener1->onTouchMoved = [](Touch* touch ,Event* event){

        auto  target = static_cast<Sprite*>(event->getCurrentTarget());
        target->setPosition(target->getPosition() + touch->getDelta());
    };

    listener1->onTouchEnded = [](Touch* touch,Event* event){
        auto target = static_cast<Sprite*>(event->getCurrentTarget());
        log("sprite onTouchesEnded..");
        target->setOpacity(25);
    };

    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, _sprite);

    this->runAction(Sequence::create(DelayTime::create(5.0f),CallFunc::create([this](){
        _spriteSaved = true;
        _sprite->retain();
        _sprite->removeFromParent();
    }),DelayTime::create(5),CallFunc::create([this](){
        _spriteSaved = false;
        this->addChild(_sprite);
        _sprite->release();
    })
                                     , NULL));

RemoveListenerAfterAddingTest

auto item1 = MenuItemFont::create("Click Me 1", [this](Ref* sender){
        auto listener = EventListenerTouchOneByOne::create();
        listener->onTouchBegan = [](Touch* touch,Event* event)->bool{
            CCASSERT(false, "Should not come here!");
            return true;
        };

        _eventDispatcher->addEventListenerWithFixedPriority(listener, -1);
        _eventDispatcher->removeEventListener(listener);

    });

    item1->setPosition(Point(0, 80));

    auto addNextButton = [this](){

        auto next = MenuItemFont::create("Please Click Me To Reset!", [this](Ref* sender){

        });

        next->setPosition(Point(100, 100));

        auto menu = Menu::create(next, NULL);
        menu->setPosition(Point(300, 100));
        menu->setAnchorPoint(Point::ZERO);
        this->addChild(menu);

    };

    auto item2 = MenuItemFont::create("Click Me 2", [=](Ref* sender){
        auto listener = EventListenerTouchOneByOne::create();
        listener->onTouchBegan = [](Touch* touch, Event* event) -> bool{
            CCASSERT(false, "Should not come here!");
            return true;
        };

        _eventDispatcher->addEventListenerWithFixedPriority(listener, -1);
        _eventDispatcher->removeEventListenersForType(EventListener::Type::TOUCH_ONE_BY_ONE);

        addNextButton();
    });

    item2->setPosition(  Point(0, 40));

    auto item3 = MenuItemFont::create("Click Me 3", [=](Ref* sender){
        auto listener = EventListenerTouchOneByOne::create();
        listener->onTouchBegan = [](Touch* touch, Event* event) -> bool{
            CCASSERT(false, "Should not come here!");
            return true;
        };

        _eventDispatcher->addEventListenerWithFixedPriority(listener, -1);
        _eventDispatcher->removeAllEventListeners();

        addNextButton();
    });
        item3->setPosition(Point(90, 90));

    auto menu = Menu::create(item1,item2,item3, NULL);
    menu->setPosition(Point(160, 160));
    addChild(menu);

DirectorEventTest

bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    Size s = Director::getInstance()->getWinSize();

    TTFConfig ttfConfig("arial.ttf", 20);

     _label1 = Label::createWithTTF(ttfConfig, "Update: 0");
    _label1->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT);
    _label1->setPosition(30,s.height/2 + 60);
    this->addChild(_label1);

    _label2 = Label::createWithTTF(ttfConfig, "Visit: 0");
    _label2->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT);
    _label2->setPosition(30,s.height/2 + 20);
    this->addChild(_label2);

 _label3 = Label::createWithTTF(ttfConfig, "Draw: 0");
    _label3->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT);
    _label3->setPosition(30,30);
    _label3->setPosition(30,s.height/2 - 20);
    _label3->retain();
    this->addChild(_label3);

     _label4 = Label::createWithTTF(ttfConfig, "Projection: 0");
    _label4->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT);
    _label4->setPosition(30,30);
    _label4->setPosition(30,s.height/2 - 60);

    this->addChild(_label4);

     _count1 = 0;
     _count2 = 0;
     _count3 = 0;
     _count4 = 0;

    auto dispatcher = Director::getInstance()->getEventDispatcher();

    auto  event1 = dispatcher->addCustomEventListener(Director::EVENT_AFTER_UPDATE, std::bind(&HelloWorld::onEvent1, this,std::placeholders::_1));
    auto event2 = dispatcher->addCustomEventListener(Director::EVENT_AFTER_VISIT, std::bind(&HelloWorld::onEvent2, this,std::placeholders::_1));
    auto event3 = dispatcher->addCustomEventListener(Director::EVENT_AFTER_DRAW, [&](EventCustom* event){
        char buf[20];
        snprintf(buf, sizeof(buf) - 1, "Draw: %d",_count3++);
        _label3->setString(buf);

    });
    event1->retain();
    event2->retain();
    event3->retain();

    scheduleUpdate();

    return true;
}

void HelloWorld::update(float delta)
{
    static float time = 0;

    time += delta;
    if(time > 0.5) {
        Director::getInstance()->setProjection(Director::Projection::_2D);
        time = 0;
    }
}

void HelloWorld::onEvent1(EventCustom *event)
{
    char buf[20];
    snprintf(buf, sizeof(buf) - 1, "Update: %d",_count1++);

    _label1->setString(buf);
}
void HelloWorld::onEvent2(EventCustom *event)
{
    char buf[20];
    snprintf(buf, sizeof(buf)-1, "Visit: %d", _count2++);
    _label2->setString(buf);
}

时间: 2024-09-29 05:50:26

Cocos2d-x3.0 触摸事件的相关文章

2.0 触摸事件

UIView不接收触摸事件的三种情况: 1.不接收用户交互 userInteractionEnabled = NO 2.隐藏 hidden = YES 3.透明 alpha = 0.0 ~ 0.01 4. 如果子视图的位置超出了父视图的有效范围, 那么子视图也是无法与用户交互的, 即使设置了父视图的 clipsToBounds = NO, 可以看懂, 但是也是无法与用户交互的 提示:UIImageView的userInteractionEnabled默认就是NO,因此UIImageView以及它

Android6.0触摸事件分发机制解读

本篇博文是Android触摸事件分发机制系列博文的第一篇,带领大家从全局掌握Android触摸事件分发机制.特别声明的是,本源码解读是基于最新的Android6.0版本. (一)Android6.0源码解读之View点击事件分发机制 (二)Android6.0源码解读之ViewGroup点击事件分发机制 (三)Android6.0源码解读之Activity点击事件分发机制 为什么要解读触摸事件分发机制 1.掌握View事件分发机制 2.为解决View滑动冲突提供理论支持 3.了解Android最

[iOS UI进阶 - 3.0] 触摸事件的基本处理

A.需要掌握和练习的 1.介绍事件类型2.通过按钮的事件处理引出view的事件处理3.响应者对象 --> UIResponder --> UIView4.view的拖拽* 实现触摸方法,打印查看* 介绍touches和UIEvent参数* 扩展:点哪去哪5.涂鸦6.手势解锁7.事件的产生和传递8.响应者链条 9.手势 B.概念 1.iOS有3种主要事件 触摸事件 加速计事件 远程控制事件 2.响应者对象 在iOS中不是任何对象都能处理事件,只有继承了UIResponder的对象才能接收并处理事

Lua中添加触摸事件

1首先,lua中的触摸事件与cocos2d中的触摸事件相似,都需要添加监听者,都需要将监听者添加到触摸事件分发器中去 local listener=cc.EventListenerTouchOneByOne:create() listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN ) listener:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_T

cocos3.0通过精灵控制精灵的触摸事件的实现

auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); auto sprite = this->getChildByTag(virTag)->getChildByTag(jumpTag); listener->onTouchBegan = CC_CALLBACK_2(MLayer::onTouchBegan, this); listener->onTouc

cocos2d-x ios游戏开发初认识(八) 触摸事件与碰撞检测

玩过植物大战僵尸都知道,要在草坪里放一朵向日葵或者其它的植物只需触摸那个植物将其拖入到想要摆放的位置,这其实就是这节要写的触摸事件.还可以发现当我们的僵尸出来的时候,我们的小豌豆会发子弹攻击僵尸,当子弹与僵尸碰撞的时候子弹自动消失,这就这节要说的碰撞检测. 下面具体看代码的实现: 做ios开发有触摸事件cocos2d同样也有 一.先覆写touch事件 .h文件 using namespace cocos2d; class MainScene:public CCLayer { private: v

registerWithTouchDispatcher 注册单点触摸事件

Doc: If isTouchEnabled, this method is called onEnter. Override it to change the way CCLayer receives touch events. Default: CCTouchDispatcher::sharedDispatcher()->addStandardDelegate(this,0); Example: void CCLayer::registerWithTouchDispatcher() { CC

cocos2d-x ios游戏开发初认识(八) 触摸事件与碰撞检測

玩过植物大战僵尸都知道,要在草坪里放一朵向日葵或者其他的植物仅仅需触摸那个植物将其拖入到想要摆放的位置,这事实上就是这节要写的触摸事件.还能够发现当我们的僵尸出来的时候,我们的小豌豆会发子弹攻击僵尸,当子弹与僵尸碰撞的时候子弹自己主动消失,这就这节要说的碰撞检測. 以下详细看代码的实现: 做ios开发有触摸事件cocos2d相同也有 一.先覆写touch事件 .h文件 using namespace cocos2d; class MainScene:public CCLayer { privat

屏幕触摸事件监听,判断上下左右的操作行为,判断方法缩小的操作行为

在手机屏幕上能够实现的人机交互行为,大致包括点击按钮,拉动滑动块,物体缩放,上下左右拉动等. 手机屏幕触摸事件的监听方法: 1.首先要设置一块布局区域,frameLayout/LinearLayout等都可以,并为布局设置id: 2.在Activity中声明相应的布局类型,并通过findViewById()方法找到该布局,然后为该布局区域设置setOnTouchListener()方法,就能监听在相应屏幕触摸操作 实现屏幕触摸事件监听的代码: private LinearLayout Land;