当前位置:Gxlcms > mysql > Cocos2d-x3.1事件实例

Cocos2d-x3.1事件实例

时间:2021-07-01 10:21:17 帮助过:24人阅读

1、触摸事件:定义NewEventDispatcher类,用于声明触摸事件 (1)单点触摸事件,在NewEventDispatcher.h中添加如下代码: //NewEventDispatcher.h#include cocos2d.hUSING_NS_CC;using namespace cocos2d;class TouchableSpriteTest : public Scene{public:

1、触摸事件:定义NewEventDispatcher类,用于声明触摸事件

(1)单点触摸事件,在NewEventDispatcher.h中添加如下代码:

//NewEventDispatcher.h
#include "cocos2d.h"
USING_NS_CC;
using namespace cocos2d;

class TouchableSpriteTest : public Scene
{
public:
    CREATE_FUNC(TouchableSpriteTest);//首先执行new操作,然后执行init函数
    virtual bool init();
    
};
在NewEventDispatcher.cpp中添加如下代码:
//NewEventDispatcher.cpp
bool TouchableSpriteTest::init()
{
    bool bRet = false;
    do{
        CC_BREAK_IF(!Scene::init());
        auto origin = Director::getInstance()->getVisibleOrigin();
        log("origin.x = %f, origin.y = %f",origin.x,origin.y);
        auto size = Director::getInstance()->getVisibleSize();
        log("size.w = %f, size.h = %f",size.width,size.height);
        
        auto containerForSprite1 = Node::create();
        
        auto sprite1 = Sprite::create("CyanSquare.png");
        sprite1->setPosition(origin+Vec2(size.width/2,size.height/2) + Vec2(-80,80));
        containerForSprite1->addChild(sprite1,10);
        addChild(containerForSprite1,11);
        
        auto sprite2 = Sprite::create("MagentaSquare.png");
        sprite2->setPosition(origin + Vec2(size.width/2, size.height/2));
        addChild(sprite2,20);
        
        auto sprite3 = Sprite::create("YellowSquare.png");
        sprite3->setPosition(Vec2(0,0));
        addChild(sprite3,1);
        //1.创建侦听事件
        auto listener1 = EventListenerTouchOneByOne::create();
        listener1->setSwallowTouches(true);
        //2.重载onTouch*函数,使用的时lambda方法,如果使用函数重载,需要在.h文件中声明。                                                            //或者在TouchableTest的头文件中声明onTouchBegan的函数重载;                                                                             //listener1->onTouchBegan = CC_CALLBACK_2(TouchableSpriteTest::onTouchBegan,this);                                                //在TouchableTest的cpp文件中重新定义。
        listener1->onTouchBegan = [](Touch* touch, Event* event)                                                                          {
            auto target = static_cast(event->getCurrentTarget());
            log("target.Tag = %d",target->getTag());
            auto locationInNode = target->convertToNodeSpace(touch->getLocation());
            auto s = target->getContentSize();
            auto rect = Rect(0,0,s.width,s.height);
            
            if(rect.containsPoint(locationInNode))
            {
                log("sprite begin...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());
            log("target.Tag = %d",target->getTag());
            target->setPosition(target->getPosition() + touch->getDelta());
            log("target.x = %lf, target.y = %lf\n touch.x = %lf,touch.y = %lf",target->getPosition().x,target->getPosition().y,touch->getDelta().x,touch->getDelta().y);
        };
        
        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);
            }
        };
        //3.加入事件侦听序列
        _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, sprite1);
        _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1->clone(), sprite2);
        _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1->clone(), sprite3);
        bRet = true;
    }while(0);
    return bRet;
}
(2)自定义触摸事件

在NewEventDispatcher.h中添加如下代码:

//.h
class CustomEvent : public Scene
{
public:
    CREATE_FUNC(CustomEvent);
    virtual bool init();
private:
    EventListenerCustom* _listener1;//自定义事件
    EventListenerCustom* _listener2;
};
在NewEventDispatcher.cpp中添加如下代码:
//.cpp
bool CustomEvent::init()
{
    bool bRet = false;
    do{
        CC_BREAK_IF(!Scene::init());
        
        auto origin = Director::getInstance()->getVisibleOrigin();
        auto size = Director::getInstance()->getVisibleSize();
        
        MenuItemFont::setFontSize(20);
        
        auto statusLabel = Label::createWithSystemFont("No custom event 1 received!", "", 20);
        statusLabel->setPosition(origin + Vec2(size.width/2, size.height-90));
        addChild(statusLabel);
        //1.创建侦听事件及回调函数,该自定义事件监听的时game_custom_event1事件
        _listener1 = 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());
        });
        //2.将侦听事件加入事件侦听序列
        _eventDispatcher->addEventListenerWithFixedPriority(_listener1, 1);
        //设置MenuItem,名字叫Send Custom Event 1,触发的事件是lambda函数,点击“Send Custom Event 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");//创建自定义事件,名字为“game_custom_event1”
            event.setUserData(buf);
            _eventDispatcher->dispatchEvent(&event);//将自定义事件加入侦听,触发事件,
            CC_SAFE_DELETE_ARRAY(buf);
        });
        sendItem->setPosition(origin + Vec2(size.width/2, size.height/2));

        
        auto statusLabel2 = Label::createWithSystemFont("No custom event 2 received!", "", 20);
        statusLabel2->setPosition(origin + Vec2(size.width/2, size.height-120));
        addChild(statusLabel2);
        //同_listener1
        _listener2 = EventListenerCustom::create("game_custom_event2", [=](EventCustom* event){
            std::string str("Custom event 2 received, ");
            char* buf = static_cast(event->getUserData());
            str += buf;
            str += " times";
            statusLabel2->setString(str.c_str());
        });
        //同_listener1
        _eventDispatcher->addEventListenerWithFixedPriority(_listener2, 1);
        
        auto sendItem2 = MenuItemFont::create("Send Custom Event 2", [=](Ref* sender){
            static int count = 0;
            ++count;
            char* buf = new char[10];
            sprintf(buf, "%d", count);
            EventCustom event("game_custom_event2");
            event.setUserData(buf);
            _eventDispatcher->dispatchEvent(&event);
            CC_SAFE_DELETE_ARRAY(buf);
        });
        sendItem2->setPosition(origin + Vec2(size.width/2, size.height/2 - 40));
        
        auto menu = Menu::create(sendItem, sendItem2, nullptr);
        menu->setPosition(Vec2(0, 0));
        menu->setAnchorPoint(Vec2(0, 0));
        addChild(menu, -1);
        
        bRet = true;
    }while(0);
    return bRet;
}

人气教程排行