ノラプログラマーの技術メモ

ネットで調べても出てこなかった情報を載せていきたい技術系ブログ。

cocos2d-xでスプライトを輝かせるエフェクトを作る方法

概要

星の画像(スプライト)の周りに星を輝かせるエフェクトを作る。

環境

windows8.1
cocos2d-x v2.2.3

手順

init関数にスケジュールを設定しておく。

bool HelloWorld::init()
{
    if ( !CCLayer::init() )
    {
        return false;
    }

    // 0.1秒ごとにstarWorldEffect関数を実行する
    this->schedule(schedule_selector(HelloWorld::starSpriteEffect), 0.1f);

・・・
}

starSpriteEffect関数には以下のソースコードを書いておく。

void HelloWorld::starSpriteEffect()
{
	// 輝かせたい画像オブジェクトをタグから取得する
	CCSprite* pSprite = (CCSprite*)this->getChildByTag(30);

	// スプライトの右上と左下の座標からランダムな座標を作る
	float min_x = pSprite->getPositionX() - (pSprite->getContentSize().width / 2);
	float max_x = pSprite->getPositionX() + (pSprite->getContentSize().width / 2);
	float min_y = pSprite->getPositionY() - (pSprite->getContentSize().height / 2);
	float max_y = pSprite->getPositionY() + (pSprite->getContentSize().height / 2);
	int width  = rand() % ((int)max_x - (int)min_x) + (int)min_x;
	int height = rand() % ((int)max_y - (int)min_y) + (int)min_y;

	// 画像スプライトを配置する
	CCSprite* pStarSprite = CCSprite::create("star.png");
	pStarSprite->setPosition(ccp(width, height));
	pStarSprite->setScale(0);
	this->addChild(pStarSprite, 30);

	// 回転しながら拡大・縮小するアニメーションを設定する
	CCActionInterval* actionScaleUp = CCScaleTo::create(0.5f, 0.5f);
	CCActionInterval* actionScaleDown = CCScaleTo::create(0.5f, 0);
	CCCallFuncN* actionMoveDone = CCCallFuncN::create(this, callfuncN_selector(HelloWorld::spriteMoveFinished));
	pStarSprite->runAction(CCSequence::create(actionScaleUp, actionScaleDown, actionMoveDone, NULL));

	CCActionInterval* actionRotate = CCRotateBy::create(1.0f, 360);
	pStarSprite->runAction(actionRotate);
}

このままでは画像スプライトが溜まっていく一方なので、アニメーションが終了したら削除する。

void HelloWorld::spriteMoveFinished(CCNode* sender)
{
	CCSprite* pSprite = (CCSprite*)sender;
	this->removeChild(pSprite, true);
}

こんな感じのエフェクトになります。

f:id:kawai_norimitsu:20140622213105p:plain