cocos2dx 3.x(多个按钮button执行同一事件的区分)

时间:2023-03-08 17:29:52
 //
// ATTGamePoker.hpp
// MalaGame
//
// Created by work on 2016/10/18.
//
// #ifndef ATTGamePoker_hpp
#define ATTGamePoker_hpp #include <stdio.h>
#include <cocos2d.h> class ATTGamePoker : public cocos2d::Layer
{ private: cocos2d::ui::Button * m_btnHold[];//五个按钮
cocos2d::Sprite * m_holdGlitter[];//发光特效/*按钮点下时出现,松开时消失*/ public: virtual bool init(); void holdCB(Ref *pSender, cocos2d::ui::Widget::TouchEventType type);//声明点击事件 CREATE_FUNC(ATTGamePoker); }; #endif /* ATTGamePoker_hpp */
 //
// ATTGamePoker.cpp
// MalaGame39
//
// Created by work on 2016/10/18.
//
// #include "ATTGamePoker.hpp"
#include <SimpleAudioEngine.h> using namespace cocos2d;
using namespace cocos2d::ui; bool ATTGamePoker::init()
{
if (!Layer::init())
{
return false;
} for (int i=; i<; i++) {
     auto soundbg=cocos2d::ui::Scale9Sprite::createWithSpriteFrameName("gobang_option_sound_off.png");
     m_btnHold[i]=ControlButton::create(soundbg);
m_btnHold[i] ->setPosition(50*i, );
m_btnHold[i] -> setEnabled(false);
m_btnHold[i]->setTag(i+);//设置tag值便于区分
m_btnHold[i]->addTouchEventListener(CC_CALLBACK_2(ATTMyGameScene::holdCB, this));
m_holdGlitter[i] = static_cast<Sprite *>(m_rootNode->getChildByName(StringUtils::format("att_8_glitter_%d",i)));
m_holdGlitter[i] ->setPosition(50*i, ); m_holdGlitter[i]->setVisible(false);//设置发光体全部隐藏
m_holdGlitter[i]->setTag(i+);
}
; return true;
} //触摸事件的实现方法
void ATTMyGameScene::holdCB(Ref *pSender, cocos2d::ui::Widget::TouchEventType type)//保牌
{ if (type == Widget::TouchEventType::BEGAN)//判断点击类型,按钮按下生效
{
int tag = ((Button*)pSender)->getTag();//通过点击事件来获取当前按钮的tag值,就是这一句话来区分当前哪个button响应来此次事件 for (int i=; i<; i++) {
m_holdGlitter[i]->setVisible(false);
if (+i==tag+) {//判断通过tag值拿到发光体精灵
m_holdGlitter[i]->setVisible(true);//让其显示
}
}
}
else if (type == Widget::TouchEventType::ENDED)//按钮松开时生效
{ for (int i=; i<; i++) { m_holdGlitter[i]->setVisible(false);//送开时全部隐藏 }
} }