【Cocos2d-x】模仿热血传奇开门动画

一、准备素材

传奇登录场景背景资源在ChrSel.wzl文件中,背景图索引是22号,开门动画是24~32号(共9张)。

至于图片提取,可以参考之前写过的一篇关于热血传奇资源文件的文章https://blog.csdn.net/aqtata/article/details/86711352

网上也有现成的工具可用。

二、优化素材

这一步不是必须的,但本着精益求精的精神,为了最大限度节省内存占用,还是写一下。

传奇开门动画图片尺寸是495 x 361,使用后发现,图片最右一个像素的竖线是黑色的(在传奇资源里,RGB(0)的颜色意味着透明)

如果直接使用就会在动画开始后出现一条黑线。

如果提取图片时将黑色转为透明的话虽然不会出现黑线,但这会使图片变大,占用更多内存。

既然用不着,就把它裁掉。

先看看我提出来图片信息,使用了透明色

【Cocos2d-x】模仿热血传奇开门动画_第1张图片

然后将宽度减去1个像素,并且将位深改为8bit

【Cocos2d-x】模仿热血传奇开门动画_第2张图片

可以看到效果很明显,无论是文件大小还是内存占用都大幅降低!

接着就进行打包,可以用TexturePacker之类的软件。

【Cocos2d-x】模仿热血传奇开门动画_第3张图片

动画一共有9张图片,打包时就发现出现一块“空地”,这就是浪费内存啊!

仔细看动画的第一帧,发现门几乎是没开的,完全可以将其移除,让动画变为8张。

【Cocos2d-x】模仿热血传奇开门动画_第4张图片

比对刚开始,优化后节省的内存还是很可观的!

三、播放动画

这一步就看看代码吧,Cocos2d-x基本使用

#include "HelloWorldScene.h"

USING_NS_CC;

Scene* HelloWorld::createScene()
{
    return HelloWorld::create();
}

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

	const auto visibleSize = Director::getInstance()->getVisibleSize();
	const auto origin = Director::getInstance()->getVisibleOrigin();

    // 背景
    auto sprite = Sprite::create("background.png");
    sprite->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
	this->addChild(sprite);

	// 监听鼠标事件
	auto mouseListener = EventListenerMouse::create();
	mouseListener->onMouseDown = CC_CALLBACK_1(HelloWorld::openDoor, this);
	_director->getEventDispatcher()->addEventListenerWithSceneGraphPriority(mouseListener, sprite);

    return true;
}

void HelloWorld::openDoor(EventMouse* event)
{
	auto animation = AnimationCache::getInstance()->getAnimation("openDoor");
	if (animation == nullptr)
	{
		const auto frameCount = 8;
		Vector frames(frameCount);
		auto frameCache = SpriteFrameCache::getInstance();
		frameCache->addSpriteFramesWithFile("door.plist");
		for (auto i = 0; i < frameCount; ++i)
		{
			auto key = StringUtils::format("%06d.png", 25 + i);
			const auto frame = frameCache->getSpriteFrameByName(key);
			frames.pushBack(frame);
		}

		animation = Animation::createWithSpriteFrames(frames);
		animation->setDelayPerUnit(1.5 / frames.size());
		AnimationCache::getInstance()->addAnimation(animation, "openDoor");
	}

	static Sprite* door = nullptr;
	if (door == nullptr)
	{
		door = Sprite::create();
		door->setAnchorPoint(Vec2(0, 0)); // 锚点设置到左下角
		door->setPosition(153, 143);
		this->addChild(door);
	}

	const auto animate = Animate::create(animation);
	door->runAction(animate);
}

【Cocos2d-x】模仿热血传奇开门动画_第5张图片

你可能感兴趣的:(Cocos2d-x)