跳跃的实现(发射子弹)

<1>

public:
    void update(float dt);
    void jump(float dt); //跳跃
    float vy;  //y方向初始速度
    float y;   //y方向坐标
    bool isRight; //是否正在向右走
public:
    CCSprite* _sp;
    
public:
    vector<CCSprite*> _bulletVec; //存储发射的子弹
    void fire(float dt); //发射子弹
    void moveBullets(float dt); //移动子弹
 
 <2> 
 

bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }
    CCSize size = CCDirector::sharedDirector()->getWinSize();
    
    _sp = CCSprite::create("Icon-57.png");
    _sp->setPosition(ccp(size.width/2, 100));
    addChild(_sp);

    vy = 300;
    y = _sp->getPositionY();
    
    isRight = true;
    scheduleUpdate();
    
    return true;
}

void HelloWorld::update(float dt)
{
    jump(dt);
    fire(dt);
    moveBullets(dt);
}

void HelloWorld::jump(float dt)
{
    float g = -5;
    _sp->setPositionY(_sp->getPositionY() + (vy + g)*dt);
     vy += g;
    if(_sp->getPositionY() <= y)
    {
        vy = 300;
    }
    
    //
    if(isRight)
        _sp->setPositionX(_sp->getPositionX() + 3);
    else
        _sp->setPositionX(_sp->getPositionX() - 3);
   
    if(_sp->getPositionX() > CCDirector::sharedDirector()->getWinSize().width - 50)
    {
        isRight = false;
    }
    if(_sp->getPositionX() < 30)
    {
        isRight = true;
    }
}

void HelloWorld::fire(float dt)
{
    static int time = 0;
    time++;
    if(time%30 == 0)
    {
       CCSprite* b = CCSprite::create("Icon-57.png");
       b->setPosition(_sp->getPosition());
       addChild(b);
       _bulletVec.push_back(b);
        time = 0;
    }
}

void HelloWorld::moveBullets(float dt)
{
    for(vector<CCSprite*>::iterator iter = _bulletVec.begin(); iter != _bulletVec.end();)
    {
        if(isRight)
           (*iter)->setPositionX((*iter)->getPositionX() + 10);
        
        else
           (*iter)->setPositionX((*iter)->getPositionX() - 10);
        
        if((*iter)->getPositionX() > CCDirector::sharedDirector()->getWinSize().width || (*iter)->getPositionX() < 0)
        {
            (*iter)->removeFromParent();
             iter = _bulletVec.erase(iter);
            
        }
        else
           iter++;
    }
}

 
 

你可能感兴趣的:(跳跃的实现(发射子弹))