首先,准备两张图片,一张是bar.png,本质上就是一个框,里面可以装血;另一张是blood.png,从名字就可以看出来,是红色的血。预览一下。**
要说明的是,在Cocos2dx中进度条的变化是通过ProgressTimer类来实现的。
auto sprite = Sprite::create("res/game/bar.png"); //创建进度框
sprite->setPosition(Point(size.width/2,size.height-20)); //设置框的位置
this->addChild(sprite); //加到默认图层里面去
auto sprBlood = Sprite::create("res/game/blood.png"); //创建血条
ProgressTimer * progress = ProgressTimer::create(sprBlood); //创建progress对象
progress->setType(ProgressTimer::Type::BAR); //类型:条状
progress->setPosition(Point(size.width/2,size.height-20));
//从右到左减少血量
progress->setMidpoint(Point(0,0.5)); //如果是从左到右的话,改成(1,0.5)即可
progress->setBarChangeRate(Point(1,0));
progress->setTag(BLOOD_BAR); //做一个标记
this->addChild(progress);
schedule(schedule_selector(GameScene::scheduleBlood), 0.1f); //刷新函数,每隔0.1秒
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
void GameScene::scheduleBlood(float delta){
auto progress = (ProgressTimer *)this->getChildByTag(BLOOD_BAR);
progress->setPercentage((((float)existLife)/PLAYER_LIFE)*100); //这里是百分制显示
if (progress->getPercentage() < 0) {
this->unschedule(schedule_selector(GameScene::scheduleBlood));
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
这里注意一下,setPercentage()函数里面的值是进度条的长度,比如说输入30,显示百分之三十的血量。每次回调如果existLife的值变化的话,就会看到血条的动态改变。上图: