Cocos2d-x中,创建Animate的几种方法

可以把常见的Animate的创建方法封装成几个函数,在使用时进行调用。

第一种方法使用do...while循环实现,不需要知道图片的数量,只要有图片的名字就可以,代码如下:

Animate* Create(const char *iName, int iloops, float delay)
{
	SpriteFrame* frame = NULL;
	Animation* animation = Animation::create();
	int index = 1;
	// 创建帧对象 
	do
	{
		String * name = String::createWithFormat("%s%d.png", iName, index++);
		frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(name->getCString());
		if (frame == NULL)
		{
			break;
		}
		animation->addSpriteFrame(frame);
	} while (true);
	animation->setDelayPerUnit(delay);  // 每帧播放间隔
	animation->setRestoreOriginalFrame(true); //播放完成之后回到初始帧
	animation->setLoops(iloops);
	// 创建动画动作
	Animate* action = Animate::create(animation);
	return action;
}
第二种方法使用for循环实现,需要知道图片的名字和数量,代码如下:

Animate* Create(const char *iName, int framecount, int iloops, float delay)
{
	SpriteFrame* frame = NULL;
	Animation* animation = Animation::create();
	// 遍历图片帧
	for (int index = 1; index <= framecount; index++)
	{
		String * name = String::createWithFormat("%s%d.png", iName, index);
		frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(name->getCString());
		animation->addSpriteFrame(frame);
	}
	animation->setLoops(iloops);
	animation->setDelayPerUnit(delay);
	animation->setRestoreOriginalFrame(true); //播放完成之后回到初始帧
	Animate* animate = Animate::create(animation);

	return animate;
}

第三种方法是先使用Vector对帧进行封装,然后创建Animation,接着创建Animate,代码如下:

Animate* Create(const char *iName, int framecount, int iloops, float delay){
	SpriteFrame* frame = NULL;
	Vector<SpriteFrame*> frameVec;

	for (int index = 1; index <= framecount; index++){
		String* name = String::createWithFormat("%s%d.png", iName, index);
		frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(name->getCString());
		frameVec.pushBack(frame); //将生成的帧添加到Vector中
	}

	Animation* animation = Animation::createWithSpriteFrames(frameVec);
	animation->setLoops(iloops);
	animation->setDelayPerUnit(delay);
<span style="white-space:pre">	</span>aniamtion->setRestoreOriginalFrame(true); //播放完成之后回到初始帧
	Animate* animate = Animate::create(animation);
	
	return animate;
}
三种方法中,还是第一种比较方便,不需要知道图片的数量。

后两种形式差不多,只是在存储帧的方法上略有不同。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值