现在的位置: 首页 > 综合 > 正文

cocos2d-x动画制作(cocos2d-x2.1)

2017年12月16日 ⁄ 综合 ⁄ 共 1612字 ⁄ 字号 评论关闭

本博客参考资料:http://www.raywenderlich.com/1271/how-to-use-animations-and-sprite-sheets-in-cocos2d

预备

用到的图片下载

TexturePacker是资源打包器,将资源打包,一起载入到游戏既方便又可以提升性能。

将下载好的图片解压缩,然后拖入到TexturePackerGUI的右边Sprites窗口中:

可以看到已经被载入了,点击工具栏Publish输出到指定目录,可以看到生成了一个.plist文件和一个png大图。

下面开始创建工程:

首先创建新工程,命名:Bears,下一步去除Box2D选项,点击完成。

将之前的两个生成文件放入到工程resource目录中。

打开HelloWorldScene.h文件,添加成员:

	cocos2d::CCSpriteBatchNode *_actors;
	cocos2d::CCSprite *_bear;

打开HelloWorldScene.cpp文件,删除掉init()中的无关代码,并且添加下列代码:

		////////////////////////////////////////////////////////////////////////////////////////////////////////
		// add bear animate
		
		CCSpriteFrameCache *cache = CCSpriteFrameCache::sharedSpriteFrameCache();
		cache->addSpriteFramesWithFile("Bears.plist");
		_actors = CCSpriteBatchNode::create("Bears.png");
		this->addChild(_actors);

		_bear = CCSprite::createWithSpriteFrameName("bear1.png");
		CCSize winSize = CCDirector::sharedDirector()->getWinSize();
		_bear->setPosition(ccp(winSize.width / 2, winSize.height / 2 ));
		_actors->addChild(_bear);
		// 为每帧创建图片
		CCArray *walkFrames = CCArray::createWithCapacity(8);
		for (int i = 1; i <= 8; i++)
		{
			CCSpriteFrame *frame = cache->spriteFrameByName(CCString::createWithFormat("bear%1d.png", i)->getCString());
			walkFrames->addObject(frame);
		}
		
		// 创建动画
		CCAnimation *walkAnimation = CCAnimation::createWithSpriteFrames(walkFrames, 1.0f / 12.0f);
		CC_BREAK_IF(!walkAnimation);
		CCAnimate* walkAnimate = CCAnimate::create(walkAnimation);
		CC_BREAK_IF(!walkAnimate);

		// 运行动画动作
		_bear->runAction(CCRepeatForever::create(walkAnimate));

制作动画的思路就是用数组CCArray保存所有帧的图片,将这个数组用来创建CCAnimation对象,进而通过CCAnimation对象来创建CCAnimate,创建了CCAnimate对象后,使用精灵来播放执行动作runAction。使用打包和批处理可以使加载动作更方便并且获得更高的性能。

运行程序可以看到屏幕上出现一个正在行走的熊,这说明动画正常执行了。

抱歉!评论已关闭.