废话少说,先上代码
定义部分:left在.h头文件做private变量。
//blood bar left = CCProgressTimer::create(CCSprite::create("progress.png")); left->setType(kCCProgressTimerTypeBar); // Setup for a bar starting from the left since the midpoint is 0 for the x left->setMidpoint(ccp(0,0)); // Setup for a horizontal bar since the bar change rate is 0 for y meaning no vertical change left->setBarChangeRate(ccp(1, 0)); left->setPosition(ccp(0, 0)); left->setAnchorPoint(ccp(0,0)); left->setPercentage(80.0); CCSprite *leftBg = CCSprite::create("progressBG.png"); leftBg->addChild(left,2); addChild(leftBg); leftBg->setPosition(ccp(200,400));
bool HelloWorld::ccTouchBegan(CCTouch* touch, CCEvent* event) { // CCLOG("... layer touch"); CCPoint l = touch->getLocation(); CCPoint location = this->convertToNodeSpace(l); float progressFrom = left->getPercentage(); float progressTo; if (location.x < 400) { progressTo = left->getPercentage() - 10; if (progressTo <= 0) { progressTo = 0; } }else{ progressTo = left->getPercentage() + 10; if (progressTo >= 100) { progressTo = 100; } } CCProgressFromTo *to2 = CCProgressFromTo::create(0.2, progressFrom, progressTo); left->runAction(to2); return false; }
说明:
实际上这个功能非常常用,而且很多变形。比如技能冷却等都可以参考CCProgress来实现。
这里的
CCProgressFromTo,继承CCActionInterval,本质上就是一个update()函数来不断的根据当前设置的progress属性,调用时间来计算 血条sprite的4个顶点vertex的位置而已。
其实如果只是progressbar的方式,参考我前面一个blog,设置
glEnable(GL_SCISSOR_TEST);
CCEGLView::sharedOpenGLView()->setScissorInPoints(x,y,w,h);
sprite.draw()
glDisable(GL_SCISSOR_TEST);
然后update血条sprite的position即可,更加简单。