动作应用1
做一个类似水果忍者的效果,每对精灵触摸一次就减血,没血后旋转消失,即需要做个进度条触摸事件+一个单精灵连续动作(callFunc+Sequence,或者RemoveSelf+Sequence)
/* 基本属性设置,血量,血条 */
int _hp;
ProgressTimer* _timer;
const int _maxHP = 88;
bool init()
{ Layer::init();
auto winSize = Director::getInstance()->getWinSize();
/* 创建一个精灵及其基本属性 */
Sprite* sprite = Sprite::create("Images/elephant1_Diffuse.png");
addChild(sprite);
sprite->setPosition(winSize.width /2, winSize.height); //把精灵放在屏幕外
sprite->setTag(100);
_hp = _maxHP;
/* 增加血条 */
/* 一个背景,一个前景,前景被ProgressTimer封装 */
Sprite* bg = Sprite::create("ccs-res/cocosui/loadingbar.png");
bg->setTag(101);
Sprite* fore = Sprite::create("ccs-res/cocosui/slidbar.png");
ProgressTimer* timer = ProgressTimer::create(fore);
timer->setType(ProgressTimer::Type::BAR);
timer->setMidpoint(Vec2(0, 0));
timer->setBarChangeRate(Vec2(1, 0));
timer->setPercentage(100);
_timer = timer; //保存进度条以便操作
/* 设定血条的父子关系 */
bg->addChild(timer); //进度条绑在背景中
sprite->addChild(bg); //背景绑在精灵中
/* 设置位置 */
Rect rcSprite =sprite->getBoundingBox();
Rect rcBg =bg->getBoundingBox();
timer->setPosition(bg->getAnchorPointInPoints());//进度条在背景中央
bg->setPosition(sprite->getAnchorPointInPoints()- Vec2(0,rcSprite.size.height / 2 + rcBg.size.height / 2)); //背景在精灵下
/* 让精灵掉下来 */
MoveBy* move = MoveBy::create(10, Vec2(0,-winSize.height));
sprite->runAction(move);
/* 触摸事件,只需要在began中设置操作 */
auto ev = EventListenerTouchOneByOne::create();
ev->onTouchBegan = [&](Touch* touch, Event*){
/* 如果大象已经死掉了,就不能再处理触摸 */
if (_hp <= 0)
return true;
Node* node =getChildByTag(100); // node是大象精灵
Vec2 touchPoint = touch->getLocation();
Rect rc =node->getBoundingBox();
if(rc.containsPoint(touchPoint))
{ _hp-= 8; // 大象少血
_timer->setPercentage(_hp*100.0/ _maxHP);
if (_hp <= 0)
{
node->getChildByTag(101)->removeFromParent();//删掉进度条
RotateBy* r = RotateBy::create(1.0f, 360);
// CallFunc* call =CallFunc::create(CC_CALLBACK_0(Sprite::removeFromParent, node)); 也可以用CallFunc,正好removeFromParent也是0参的
RemoveSelf* remove = RemoveSelf::create();//专门的删除动作,会调用RemoveFromParent
Sequence* seq = Sequence::create(r, remove, NULL);
node->stopAllActions();//先停止MoveBy动作
node->runAction(seq); //运行旋转消失动作
}
}
return true;
};
this->_eventDispatcher->addEventListenerWithSceneGraphPriority(ev,this);
return true;}
总结:
1. RemoveSelf动作
2. 精灵之间的绑定关系
3. 0参的callfunc和Sequence组合