用于预加载资源的缓冲区有:
CCTextureCache(图片纹理),CCSpriteFrameCache(精灵)
CCAnimationCache(动画),CCShaderCache(着色器)
请先参阅简单动画实现:http://blog.csdn.net/zlqqhs/article/details/9235551
所用到的图片资源:
步骤:
1.新建一个Cocos2d-x工程并保证能成功运行
2.在include下添加StaticData.h文件,添加代码
3.在source下添加StaticData.cpp文件,添加代码
4.在HelloWorldScene.cpp文件中添加和修改代码
1.新建一个Cocos2d-x工程,将所用到的图片资源放
到工程中,运行程序,保证程序能够成功运行
2.在include下添加StaticData.h文件,添加代码
#ifndef __STATICDATA_H__
#define __STATICDATA_H__
#include "cocos2d.h"
class StaticData
{
public:
static void load();
};
#endif
#include "StaticData.h"
#include "cocos2d.h"
using namespace cocos2d;
void StaticData::load()
{
//1.读取2D纹理信息
CCTexture2D *texture = CCTextureCache::sharedTextureCache()->addImage("items.png");
//2.记录单帧信息
CCSpriteFrame* m_frame1 = CCSpriteFrame::createWithTexture(texture, CCRectMake(/*0, 128, 32, 32*/64, 160, 64, 16));
CCSpriteFrame* m_frame2 = CCSpriteFrame::createWithTexture(texture, CCRectMake(/*32, 128, 32, 32*/ 64, 176, 64, 16));
CCSpriteFrame* m_frame3 = CCSpriteFrame::createWithTexture(texture, CCRectMake(/*64, 128, 32, 32*/64, 192, 64, 16));
CCSpriteFrame* m_frame4 = CCSpriteFrame::createWithTexture(texture, CCRectMake(/*96, 128, 32, 32*/64, 208, 64, 16));
//3.生成逐帧数组
CCArray *animFrames = CCArray::create();
animFrames->addObject(m_frame1);
animFrames->addObject(m_frame2);
animFrames->addObject(m_frame3);
animFrames->addObject(m_frame4);
//4.动画信息,设置间隔时间为0.5
CCAnimation *animation = CCAnimation::createWithSpriteFrames(animFrames, 0.5f);
//将CCAnimation加到CCAnimationCache缓冲区中
CCAnimationCache::sharedAnimationCache()->addAnimation(animation, "animation");
//将CCSpriteFrame加到CCAnimationCache缓冲区中
CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFrame(m_frame1, "m_frame1");
}
4.在HelloWorldScene.cpp文件中添加和修改代码
添加代码:
#include "StaticData.h"
删除bool HelloWorld::init()下do代码块中的代码,替换为:
CC_BREAK_IF(! CCLayer::init());
StaticData::load();
/***第一种方法***/
//先取得一个CCSpriteFrame,再通过取得的CCSpriteFrame创建一个CCSprite
CCSpriteFrame *m_frame1 = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("m_frame1");
CCSprite *m_sprite = CCSprite::createWithSpriteFrame(m_frame1);
m_sprite->setPosition(ccp(100, 100));
this->addChild(m_sprite);
/***第二种方法***/
//通过名字取得CCSpriteFrame
//CCSprite *m_sprite = CCSprite::createWithSpriteFrameName("m_frame1");
//m_sprite->setPosition(ccp(200, 200));
//this->addChild(m_sprite);
//通过名字取得CCAnimation
CCAnimation *animation = CCAnimationCache::sharedAnimationCache()->animationByName("animation");
CCAnimate *animate = CCAnimate::create(animation);
m_sprite->runAction(CCRepeatForever::create(animate));
bRet = true;
此为简单做法,通常情况下的做法是与plist配合使用,
与plist配合使用可提高维护性,简易化修改和增加