cocos2d-xで画像を動かす

追記

画像配置コード確認

  • 今までのサンプルでも参考にしているHelloWorldの全画面に出ている画像をどう出しているか確認する
  • コードは前回ボタンを追加したコードにそのまま追加。なのでボタン2つでてる
    // add "HelloWorld" splash screen"
    CCSprite* pSprite = CCSprite::create("HelloWorld.png");

    // position the sprite on the center of the screen
    pSprite->setPosition( ccp(size.width/2, size.height/2) );

    // add the sprite as a child to this layer
    this->addChild(pSprite, 0);

左右に揺らしてみる

  • 正弦の値を使って揺らす

追加するメンバ

  • ひと揺れの中のフレーム番号(ループ変数)
  • 動かす画像オブジェクト
  • 定期的に呼び出される関数
class HelloWorld : public cocos2d::CCLayer
{
private:
    cocos2d::CCLabelTTF *mLabel; // ボタンを押したときにテキストを変更するラベル
    int mLoopCount; // ひと揺れの中のフレーム番号
    cocos2d::CCSprite *mSprite; // 動かす画像オブジェクト
    
public:
    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
    virtual bool init();
    
    // there's no 'id' in cpp, so we recommand to return the exactly class pointer
    static cocos2d::CCScene* scene();
    
    // a selector callback
    void menuCloseCallback(CCObject* pSender);
    
    // new callback function
    void menuTextChangeCallback(CCObject *pSender);

    // move sprite logic
    void gameLogic();
    
    // implement the "static node()" method manually
    LAYER_CREATE_FUNC(HelloWorld);
};

画像オブジェクト保存

    // add "HelloWorld" splash screen"
    CCSprite* pSprite = CCSprite::create("HelloWorld.png");
    this->mSprite = pSprite; // 画像オブジェクトを保存

毎フレーム座標更新

    this->schedule( schedule_selector(HelloWorld::gameLogic), 1.0 / 60.0 );
    
    return true;
}
  • 画像移動処理実装
    • 久しぶりに書いたら三角関数忘れてたのでコード汚いけどこんな感じ
void HelloWorld::gameLogic()
{
    float x = 0;
    CCSize size = CCDirector::sharedDirector()->getWinSize();
    const float PI = 3.1415f;
    int max_loop_count = 60 * 1;
    float cos_value = cosf(PI * ((float)this->mLoopCount++ / (float)max_loop_count));
    x = (float)size.width * cos_value;
    
    if( this->mLoopCount > (max_loop_count * 2) )
    {
        this->mLoopCount = 0;
    }
    
    this->mSprite->setPosition( ccp( x + size.width / 2, size.height / 2) );
    
}

画面

  • 静止画だけど左右に揺れてる

f:id:kambayashi:20120729154448p:plain