首页 > 代码库 > Cocos2d-x3.0 触摸事件

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);
}

技术分享












Cocos2d-x3.0 触摸事件