概述:
cocos2d 做動畫特效,利用cocos2d的Action類,非常簡單。直接調用node->runAction(),即可實現相應的特效。
先上一張action 類圖:
本次暫不介紹ccFollow與ccSpeed。除了這兩個類之外,常用的動作父類,即時動作(ccActionInstant)-瞬間完成,延時動作(ccActionInterval)-逐漸完成。
使用示例:
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
Node* sp = Sprite::create("HelloWorld.png");
sp->setPosition(Point(visibleSize.width/2,visibleSize.height/2));
this->addChild(sp);
1.執行動作
sp ->runAction(MoveTo::create(1,Vec2(100,100)));
這樣就給精靈一個MoveTo動作,執行時間是1s,移動到100,100的位置。
2.動作反轉
sp ->runAction(MoveTo::create(1,Vec2(100,100))->reverse());
給Action動作執行一個reverse()方法,就能讓動作反轉執行
3.動作重複
//如果讓Node在1s內旋轉180度
sp -runAction(RotateBy::create(1,180));
//重複執行此動作3次:
sp -runAction(Repeate::create(RotateBy::create(1,180)));
//永久重複執行動作
sp -runAction(RepeateForever::create(RotateBy::create(1,180)));
4.混合動作同時執行
sp ->runAction(Spawn::create(MoveTo::create(1,Vec2(100,100)),RotateBy::create(1,360),NULL));
使用Spawn可以實現多個動作同時進行,讓label1s內移動到100,100的位置同時自身旋轉一週。並且在末尾要寫一個NULL,能標識動作組的結束
5.混合動作順序執行
sp ->runAction(Sequence::create(MoveTo(1,Vec2(100,100)),RotateBy::create(1,360),NULL));
其實Sequence跟Spawn使用方法一樣,一個是同時,一個是順序
Action 動作完成監聽
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//獲取屏幕的尺寸、位置信息等
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
Node* sp = Sprite::create("HelloWorld.png");
sp->setPosition(Point(visibleSize.width/2,visibleSize.height/2));
this->addChild(sp);
//設置精靈,並把精靈添加到舞臺的中央
Sprite*sprite=Sprite::create("HelloWorld.png");
sprite->setPosition(Point(visibleSize.width/2,visibleSize.height/2));
this->addChild(sprite);
//動作1
FiniteTimeAction* action1=Blink::create(1.0f,3);
//動作2
FiniteTimeAction* action2=MoveBy::create(1.0f,ccp(0,100));
CallFunc *callFunc=CCCallFunc::create(this,callfunc_selector(HelloWorld::actionCallback));
//合併上述動作,並應用到精靈
FiniteTimeAction* sequence=CCSequence::create(action1,action2,callFunc,NULL);
sprite->runAction(sequence);
return true;
}
void HelloWorld::actionCallback()
{
//動畫結束
}
希望對您有所幫助!