cocos 2dx 3.12 学习笔记(四) ButtonTest

按钮事件  


ButtonTestLayer.h


#ifndef _BUTTON_TEST_LAYER_H_
#define _BUTTON_TEST_LAYER_H_


#include "cocos2d.h"
#include "ui\CocosGUI.h"    //引入  CocosGui
USING_NS_CC;

class ButtonTestLayer : public cocos2d::Layer
{
public:
	static cocos2d::Scene* createScene();
	CREATE_FUNC(ButtonTestLayer);

	virtual bool init();
	//button点击事件
	void btnClickCallback(cocos2d::Ref * pSpender);
	//button触摸事件
	void btnTouchCallback(cocos2d::Ref * sender,cocos2d::ui::Widget::TouchEventType type );
private:
	cocos2d::ui::Button * m_pBtn = nullptr;

};


#endif


ButtonTestLayer.app


#include "ButtonTestLayer.h"

using namespace cocos2d::ui;   //引入 cocos2d ui
Scene* ButtonTestLayer::createScene()
{
	auto scene = Scene::create();
	auto layer = ButtonTestLayer::create();
	scene->addChild(layer);
	return scene;
}

bool ButtonTestLayer::init()
{
	Layer::init();

	auto visibleSize = Director::getInstance()->getVisibleSize();
	float x = 0;
	float y = 0;
	x = visibleSize.width / 2;
	y = visibleSize.height / 2;

	m_pBtn = Button::create("CloseNormal.png","CloseSelected.png");  //创建button,两个图片实现一个是平常状态,另外一个是点击时候的状态
	//若此处只输入一个图片文件,会自动生成一个动画。
	this->addChild(m_pBtn);

	m_pBtn->setPosition(Vec2(x, y));//设置button的位置
	m_pBtn->addClickEventListener(CC_CALLBACK_1(ButtonTestLayer::btnClickCallback,this));
	m_pBtn->addTouchEventListener(CC_CALLBACK_2(ButtonTestLayer::btnTouchCallback, this));
	//button回调函数
	return true;


}

//ButtonTestLayer::btnClickCallback方法
void ButtonTestLayer::btnClickCallback(cocos2d::Ref * pSpender)
{
	Node * pNode = dynamic_cast<Node*>(pSpender);
	log("Button click");
}
//ButtonTestLayer::btnTouchCallback方法
void ButtonTestLayer::btnTouchCallback(cocos2d::Ref * sender, cocos2d::ui::Widget::TouchEventType type)
{
	if (type == Widget::TouchEventType::BEGAN)
	{
		log("began");
	}
	if (type == Widget::TouchEventType::MOVED)
	{
		log("moved");
	}
	if (type == Widget::TouchEventType::ENDED)
	{
		log("ended");
	}
	//在点击button即可调用 BRGAN,之后移动即可调用MOVED,最后必须移动回按钮,才能调用 ENDED方法
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值