Cocos2d-x学习笔记
动画又可以分为场景过渡动画和帧动画。
帧动画
帧动画就是按照一定时间间隔、一定的顺序、一帧一帧地显示图片。在Cocos2d-x中播放帧动画设计两个类:Animate和Animation。Animation是动画类,它保存很多动画帧,Animate类是动作类继承于ActionInterval类,属于间隔动作类,它的作用是将Animateion定义的动画转换成动作进行执行。
实例
HelloWorld.h文件
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
class HelloWorld : public cocos2d::Layer
{
bool isPlaying;//播放标识,ture说明正在播放,false说明停止播放
cocos2d::Sprite * sprite;
public:
static cocos2d::Scene* createScene();
virtual bool init();
// a selector callback
void onAction(cocos2d::Ref * pSender);
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
};
#endif // __HELLOWORLD_SCENE_H__
HelloWorld.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();
SpriteFrameCache::getInstance()->addSpriteFramesWithFile("run.plist");
auto background = Sprite::createWithSpriteFrameName("background.png");
background->setAnchorPoint(Vec2::ZERO);
this->addChild(background, 0);
sprite = Sprite::createWithSpriteFrameName("h1.png");
sprite->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
this->addChild(sprite);
isPlaying = false;
//toggle菜单
auto goSprite = Sprite::createWithSpriteFrameName("go.png");
auto stopSprite = Sprite::createWithSpriteFrameName("stop.png");
auto goToggleMenuItem = MenuItemSprite::create(goSprite, goSprite);
auto stopToggleMenuItem = MenuItemSprite::create(stopSprite, stopSprite);
auto toggleMenuItem = MenuItemToggle::createWithCallback(CC_CALLBACK_1(HelloWorld::onAction, this), goToggleMenuItem, stopToggleMenuItem, NULL);
toggleMenuItem->setPosition(Director::getInstance()->convertToGL(Vec2(930, 540)));
auto mn = Menu::create(toggleMenuItem, NULL);
mn->setPosition(Vec2::ZERO);
this->addChild(mn);
return true;
}
void HelloWorld::onAction(Ref * pSender)
{
if (!isPlaying)
{
//动画开始
Animation * animation = Animation::create();
//循环将精灵帧加入到animation对象中
for (int i = 1; i <= 4; i++)
{
__String * frameName = __String::createWithFormat("h%d.png", i);
log("frameName = %s", frameName->getCString());
SpriteFrame * spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(frameName->getCString());
animation->addSpriteFrame(spriteFrame);
animation->setDelayPerUnit(0.15f);//设置两个帧播放时间
animation->setRestoreOriginalFrame(true);//动画执行后还原初状态
}
Animate * action = Animate::create(animation);
sprite->runAction(RepeatForever::create(action));
//动画结束
isPlaying = true;
}
else
{
sprite->stopAllActions();
isPlaying = false;
}
}