Cocos2dx V3.x 实现人物血条 (附源代码)

实现思想用progressTimer来根据血量来更新血条的长度

不多废话代码在下面。

.h

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__


#include "cocos2d.h"
USING_NS_CC;
class HelloWorld : public cocos2d::Layer
{
public:

    // there's no 'id' in cpp, so we recommend returning the class instance pointer
    static cocos2d::Scene* createScene();


    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
    virtual bool init();  
    
    
    // implement the "static create()" method manually
    CREATE_FUNC(HelloWorld);
private:
int m_num;
int m_curNum;
ProgressTimer* blood;
void bloodCallBack(Ref* pSender);
void schedleUpdate(float dt);
HelloWorld() :m_num(100), m_curNum(100), blood(NULL){};
};


#endif // __HELLOWORLD_SCENE_H__

.cpp

#include "HelloWorldScene.h"


USING_NS_CC;
Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();
    
    // 'layer' is an autorelease object
    auto layer = HelloWorld::create();


    // add layer as a child to scene
    scene->addChild(layer);


    // return the scene
    return scene;
}


// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }
    
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();
//blood bg
auto bloodBg = Sprite::create("blood1.png");
bloodBg->setPosition(visibleSize.width * 0.5,visibleSize.height * 0.5);
this->addChild(bloodBg);
//progress
blood = ProgressTimer::create(Sprite::create("blood2.png"));
blood->setPosition(visibleSize.width * 0.5,visibleSize.height * 0.5);
blood->setType(ProgressTimer::Type::BAR);//条形
blood->setPercentage(100.0f);
blood->setBarChangeRate(Vec2(1,0));//设置血条改变的方向Vec2(0,1)表示竖向  Vec2(1.0)是横向的
blood->setMidpoint(Vec2(0,1));
this->addChild(blood);
this->schedule(schedule_selector(HelloWorld::schedleUpdate), 1.0f);
    return true;
}
void HelloWorld::schedleUpdate(float dt){
auto call = CallFuncN::create(CC_CALLBACK_1(HelloWorld::bloodCallBack,this));
this->runAction(call);
}
void HelloWorld::bloodCallBack(Ref* pSender){
m_curNum -= 10;
blood->setPercentage(m_curNum);
log("11111111");
if (m_curNum == 0)
{
log("22222222");
}

}

最终的实现效果

Cocos2dx V3.x 实现人物血条 (附源代码)_第1张图片

下载地址:http://download.csdn.net/detail/u010983974/7795377

你可能感兴趣的:(Class,cocos2dx,cpp,cocos2d-x,人物)