博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Cocos2d-x3.0 触摸事件
阅读量:5139 次
发布时间:2019-06-13

本文共 10884 字,大约阅读时间需要 36 分钟。

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
(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
(event->getCurrentTarget()); target->setPosition(target->getPosition() + touch->getDelta()); }; listener1->onTouchEnded = [=](Touch* touch,Event* event){ auto target = static_cast
(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
(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
(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
(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
(event->getCurrentTarget()); target->setPosition(target->getPosition() + touch->getDelta()); }; listener1->onTouchEnded = [](Touch* touch,Event* event){ auto target = static_cast
(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);}

转载于:https://www.cnblogs.com/zsychanpin/p/6719328.html

你可能感兴趣的文章
使用Redshift渲染器,怎么选电脑配置!
查看>>
vue-element:文件上传七牛之key和异步的问题
查看>>
【BZOJ2631】tree (LCT)
查看>>
python常用代码笔记
查看>>
机器学习之路:python 集成分类器 随机森林分类RandomForestClassifier 梯度提升决策树分类GradientBoostingClassifier 预测泰坦尼克号幸存者...
查看>>
AJAX 跨源 HTTP 请求
查看>>
Web 项目系列之浏览器机制(一)
查看>>
IOS真机调试
查看>>
IOS正则表达式的用法简介
查看>>
day31 python学习 并发编程之多进程理论部分
查看>>
Uploadify jquery+flash+UploadHandler.ashx
查看>>
Java-P:对象创建
查看>>
IIS 配置
查看>>
软件人机界面设计
查看>>
requests模块下载视频 显示进度和网速
查看>>
Elasticsearch 学习之 分片未分配原因
查看>>
.NET项目从CI到CD-Jenkins_Pipeline的应用
查看>>
E2.(b)
查看>>
ini 解析库,config 解析库不完全列表
查看>>
awk常见操作整理(更新)
查看>>