首页 > 代码库 > cocos2dx 3.0(多个按钮button执行同一事件的区分)

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

 1 //
 2 //  ATTGamePoker.hpp
 3 //  MalaGame
 4 //
 5 //  Created by work on 2016/10/18.
 6 //
 7 //
 8 
 9 #ifndef ATTGamePoker_hpp
10 #define ATTGamePoker_hpp
11 
12 #include <stdio.h>
13 #include <cocos2d.h>
14 
15 
16 class ATTGamePoker : public cocos2d::Layer
17 {
18     
19 private:
20     
21     cocos2d::ui::Button * m_btnHold[5];//五个按钮
22     cocos2d::Sprite * m_holdGlitter[5];//发光特效/*按钮点下时出现,松开时消失*/
23     
24 public:
25     
26     virtual bool init();
27     
28     void holdCB(Ref *pSender, cocos2d::ui::Widget::TouchEventType type);//声明点击事件
29 
30     CREATE_FUNC(ATTGamePoker);
31     
32 };
33 
34 #endif /* ATTGamePoker_hpp */

 

 

 1 //
 2 //  ATTGamePoker.cpp
 3 //  MalaGame39
 4 //
 5 //  Created by work on 2016/10/18.
 6 //
 7 //
 8 
 9 #include "ATTGamePoker.hpp"
10 #include <SimpleAudioEngine.h>
11 
12 using namespace cocos2d;
13 using namespace cocos2d::ui;
14 
15 bool ATTGamePoker::init()
16 {
17     if (!Layer::init())
18     {
19         return false;
20     }
21     
22     for (int i=0; i<5; i++) {
23      auto soundbg=cocos2d::ui::Scale9Sprite::createWithSpriteFrameName("gobang_option_sound_off.png");
24      m_btnHold[i]=ControlButton::create(soundbg);
25         m_btnHold[i] ->setPosition(50*i, 60);
26         m_btnHold[i] -> setEnabled(false);
27         m_btnHold[i]->setTag(i+100);//设置tag值便于区分
28         m_btnHold[i]->addTouchEventListener(CC_CALLBACK_2(ATTMyGameScene::holdCB, this));
29         m_holdGlitter[i] = static_cast<Sprite *>(m_rootNode->getChildByName(StringUtils::format("att_8_glitter_%d",i)));
30         m_holdGlitter[i] ->setPosition(50*i, 60);
31 
32         m_holdGlitter[i]->setVisible(false);//设置发光体全部隐藏
33         m_holdGlitter[i]->setTag(i+200);
34     }
35 ;
36     
37     
38     
39     
40     
41     return true;
42 }
43 
44 
45 //触摸事件的实现方法
46 void ATTMyGameScene::holdCB(Ref *pSender, cocos2d::ui::Widget::TouchEventType type)//保牌
47 {
48     
49     if (type == Widget::TouchEventType::BEGAN)//判断点击类型,按钮按下生效
50     {
51         int tag = ((Button*)pSender)->getTag();//通过点击事件来获取当前按钮的tag值,就是这一句话来区分当前哪个button响应来此次事件
52         
53         for (int i=0; i<5; i++) {
54             m_holdGlitter[i]->setVisible(false);
55             if (200+i==tag+100) {//判断通过tag值拿到发光体精灵
56                 m_holdGlitter[i]->setVisible(true);//让其显示
57             }
58         }
59     }
60     else if (type == Widget::TouchEventType::ENDED)//按钮松开时生效
61     {
62         
63         for (int i=0; i<5; i++) {
64             
65             m_holdGlitter[i]->setVisible(false);//送开时全部隐藏
66             
67         }
68     }
69         
70     
71 
72 }

 

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