技能按钮
- 技能按钮类:继承于按钮类
- 使用观察者模式(一对多的关系):底层实质就是函数指针
SkillButton.h
#ifndef _SkillButton_H_
#define _SkillButton_H_
#include "Ui/CocosGUI.h"
class SkillButton :public cocos2d::ui::Button{
public:
SkillButton(float coldTime):
coldTime(coldTime),
isCold(false),
onColdBegan(nullptr),
onColdEnded(nullptr)
{
}
static SkillButton* create(
float coldTime,
const std::string& normalImage,
const std::string& selectedImage = "",
const std::string& disableImage = "",
TextureResType texType = TextureResType::LOCAL);
bool init(
const std::string& normalImage,
const std::string& selectedImage = "",
const std::string& disableImage = "",
TextureResType texType = TextureResType::LOCAL);
public:
typedef std::function<void()> ccColdBeganCallback;
typedef std::function<void()> ccColdEndedCallback;
ccColdBeganCallback onColdBegan;
ccColdEndedCallback onColdEnded;
private:
float coldTime;
bool isCold;
};
#endif
SkillButton.cpp
#include "SkillButton.h"
#include "cocos2d.h"
using namespace cocos2d::ui;
using namespace cocos2d;
SkillButton* SkillButton::create(
float coldTime,
const std::string& normalImage,
const std::string& selectedImage,
const std::string& disableImage,
TextureResType texType) {
SkillButton* ret = new(std::nothrow) SkillButton(coldTime);
if (ret && ret->init(normalImage, selectedImage, disableImage, texType)) {
ret->autorelease();
} else {
delete ret;
ret = nullptr;
}
return ret;
}
bool SkillButton::init(
const std::string& normalImage,
const std::string& selectedImage,
const std::string& disableImage,
TextureResType texType) {
if (!Button::init(normalImage, selectedImage, disableImage, texType)) {
return false;
}
Sprite* sp = Sprite::create(normalImage);
sp->setColor(Color3B::GRAY);
ProgressTimer* progressTimer = ProgressTimer::create(sp);
progressTimer->setAnchorPoint(Vec2::ZERO);
progressTimer->setReverseDirection(true);
this->addChild(progressTimer);
this->addClickEventListener([this, progressTimer](Ref*) {
if (!isCold) {
if (onColdBegan != nullptr) {
onColdBegan();
}
isCold = true;
setTouchEnabled(false);
auto progressFromTo = ProgressFromTo::create(coldTime, 100, 0);
auto callFunc = CallFunc::create([this]() {
if (onColdEnded != nullptr) {
onColdEnded();
}
isCold = false;
setTouchEnabled(true);
});
auto seqAct = Sequence::create(progressFromTo, callFunc, nullptr);
progressTimer->runAction(seqAct);
}
});
return true;
}