Cannot place a function callback inside Touch event?

What’s the proper way of doing this? I have letter buttons inside ‘_letterTilesPool’ Vector. so when i press those buttons , I want to execute someFunctions() … but I cant place a function inside. it generates error

in GameScene.cpp:

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

for(auto pic: _letterTilesPool){  //attach TOUCHEVENT to all sprite inside my vector
    
    listener1->onTouchBegan = [pic](Touch* touch, Event* event){
   
    auto target = static_cast<CCTiles*>(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("you pressed letter %c", target->getLetterVal());
        checkForMatches();  // <---------- ERROR 
        target->setOpacity(180); // works fine,
        
        return true;
    }
    return false;
};

ERROR says:
‘this’ cannot be implictly captured in this context.

What’s the proper way of doing this?

use

listener1->onTouchBegan = [&](.....) {

   this->checkForMatches();

};
1 Like

ok i’ll try that :smile:

@ruire
im curious … what do you mean when you put ‘&’ inside of 'listener1->onTouchBegan = & {

or sometimes they put ‘=’ inside listener1->onTouchEnded = & {

or sometimes leave it empty listener1->onTouchBegan = {

@ruire it’s working, :slight_smile: thnks!

Hi, @reyanthonyrenacia, you can read it here… http://en.cppreference.com/w/cpp/language/lambda#Lambda_capture

1 Like

Well you got your way of doing this…
Did you use lambda function?

But did you get the reason why your original implementation was not working?

Here is the reason…
since you’ve not mentioned anything before

It means that this is implicit which error also says…
It didn’t work because you should have done
target->checkForMatches();
instead of
this->checkForMatches();

And… did you notice that why we are using
event->getCurrentTarget()… … It is because ‘this’ is not meant to work inside touch functions implementations :smile:

If you’ve not made work your original implementation then try that… it would also work
:smiley:

@catch_up ok partner, will look into that :smile: