LoginSignup
1
0

More than 5 years have passed since last update.

親レイヤーから子レイヤーへのコールバック渡し[Cocos2d-x]

Last updated at Posted at 2017-11-23

内容

親レイヤーの上に子レイヤーをのせて子レイヤーから親レイヤーの処理をさせたい場合
親レイヤーで渡したい処理を書いて子レイヤーに渡す
前回のSceneへの変数渡しの応用

親レイヤーから子レイヤー作成

ParentSample.cpp
void ParentSample::sampleCreate(){
    Sample* sample = Sample::create(CC_CALLBACK_0(ParentSample::test, this));
    this->addChild(sample);
}

void ParentSample::test(){
    //処理したいプログラム
}

子レイヤー作成

Sample.h
#ifndef __Sample__
#define __Sample__

#include "cocos2d.h"
#include "XTLayer.h"

typedef std::function<void(cocos2d::Ref*)> DataCallback;

class Sample : public XTLayer
{
private:
    //上部typedefで格納部を定義
    DataCallback callData;

public:
    //いろいろ省略
    virtual bool init(const DataCallback& call);
    static cocos2d::Scene* scene(const DataCallback& call);
    static Sample* create(const DataCallback& call);

    //いろいろ省略
};

#endif /* defined(__Sample__) */
Sample.cpp
#include "Sample.h"

//いろいろ省略

Scene* Sample::scene(const DataCallback& call){

    Scene *scene = Scene::create();
    Information *layer = Sample::create(call);
    scene->addChild(layer);

    return scene;
}

Sample* Sample::create(const DataCallback& call){
    Information* ret = new Sample();

    if (ret && ret->init(call)){
        ret->autorelease();
        return ret;
    }else{
        CC_SAFE_DELETE(ret);
        return NULL;
    }
}

bool Sample::init(const DataCallback& call){

    if (!Layer::init()) return false;

    auto listener = EventListenerTouchOneByOne::create();
    listener->onTouchBegan = CC_CALLBACK_2(Sample::onTouchBegan, this);
    listener->onTouchMoved = CC_CALLBACK_2(Sample::onTouchMoved, this);
    listener->onTouchEnded = CC_CALLBACK_2(Sample::onTouchEnded, this);
    listener->setSwallowTouches(true);
    this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);

    //コールバックのデータを格納
    callData = call;

    //このプログラムで親から渡したプログラムが動く
    if(callData) callData(this);

    return true;
}
//いろいろ省略

応用例

モーダルレイヤー
その他にもいろいろ使い道がある

次回

何か考える

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0