I created class for uiButton creation, there is three function as following; I created button class there is 3 function in class as following;
void MyButtonClass::Create(const std::string &buttonImage, cocos2d::Layer *layer)
{
myButton = ui::Button::create(buttonImage, buttonImage);
layer->addChild(myButton, 100);
}
void MyButtonClass::SetPosition(float xPosition, float yPosition)
{
myButton->cocos2d::Node::setPosition(xPosition, yPosition);
}
void MyButtonClass::SetTouchListener(Ref *sender, SEL_TouchEvent *selector)//There is problem
{
myButton->addTouchEventListener(sender, selector);
}
How can I set TouchListener? I looked parameters from library but it is not working.
for example create button from my gamescene;
button.Create("Play.png", this);
button.SetPosition(100, 200);
button.SetTouchListener(CC_CALLBACK_1(GameScene::Play, this));//Exception: No viable conversion from '__bind<void (GameScene::*)(cocos2d::Ref *), GameScene *, std::__1::placeholders::__ph<1> &>' to 'cocos2d::Ref *'
I think you used the wrong overload for your situation. You'll want to use the void addTouchEventListener (const ccWidgetTouchCallback &callback)
overload.
The reason this doesn't work is because no callback is bound to myButton
. You need to bind a custom callback:
Assuming your button class inherits from a ::cocos2d::ui::Button
or ::cocos2d::ui::Widget
, you need to assign a callback with
the Widget::addTouchEventListener() method.
myButton->addTouchEventListener(this, toucheventselector(MyButtonClass::touchEvent));
The callback MyButtonClass::touchEvent
will be invoked when a touchevent for the button is received.
For example:
void MyButtonClass::SetTouchListener(Ref *sender, SEL_TouchEvent *selector)//There is problem
{
myButton->addTouchEventListener([](Ref*, Widget::TouchEventType){
// Simple callback for touch
int n = 0;
});
}
EDIT
The alternative is to use the methods in myButton
by setting one or more of the following:
onTouchBegan (Touch *touch, Event *unusedEvent)
onTouchMoved (Touch *touch, Event *unusedEvent)
onTouchEnded (Touch *touch, Event *unusedEvent)
onTouchCancelled (Touch *touch, Event *unusedEvent)
Check out the codos2d-x doc for the ui::Button class
There is also an example of onTouchBegan
and onTouchEnded
here.
Instead of listener1
in this example, you can use myButton
.