原理:
Cocos2D中有个导演控制整个游戏流程,导演将场景添加到屏幕上,场景中有各种各样的演员。
先通过显示一张图片来看看Cocos2D游戏的流程:
AppDelegate.cpp
[cpp]
bool AppDelegate::applicationDidFinishLaunching()
{
// 初始化导演
CCDirector *pDirector = CCDirector::sharedDirector();
pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
// 打开FPS
pDirector->setDisplayStats(true);
// 设置FPS the default value is 1.0/60 if you don't call this
pDirector->setAnimationInterval(1.0 / 60);
// 创建一个场景
CCScene *pScene = GameScence::scene();
// 运行此场景
pDirector->runWithScene(pScene);
return true;
}
上边的代码添加了一个场景GameScence,下面看看具体实现:
GameScence.h
[cpp]
#include "cocos2d.h"
#include "Box2D/Box2D.h"
class GameScence : public cocos2d::CCLayer
{
public :
bool init();
//必须重写scene()
static cocos2d::CCScene* scene();
//相当于create函数,是重写了CCLayer里的create函数
CREATE_FUNC(GameScence);
};
GameScence.cpp
[cpp]
#include "GameScene.h"
using namespace cocos2d;
CCScene* GameScence::scene()
{
CCScene * scene = NULL;
do
{
scene=CCScene::create();
GameScence* gameScene=GameScence::create();
scene->addChild(gameScene);
}while(0);
return scene;
};
bool GameScence::init()
{
bool bRet = false;
do
{
//从图片创建一个精灵
CCSprite* pSprite = CCSprite::create("bg.png");
//获取屏幕大小
CCSize size = CCDirector::sharedDirector()->getWinSize();
// 设置精灵在场景中的位置,坐标从左下角0,0
pSprite->setPosition(ccp(size.width/2, size.height/2));
// 添加精灵到场景中
this->addChild(pSprite, 0);
}while(0);
bRet=true;
return bRet;
};
代码中有注释,就不在重复叙述了,
下面是效果图:
怎么让其显示一个动态的精灵呢,下面是修改后的init()
[cpp]
bool GameScene::init()
{
bool bRet = false;
do
{
CCSprite* pMap = CCSprite::create("bg.png");
CCSize size = CCDirector::sharedDirector()->getWinSize();
pMap->setPosition(ccp(size.width/2, size.height/2));
this->addChild(pMap, 0);
CCSprite* sprite ;
CCArray* pSpriteArray=CCArray::createWithCapacity(4);
for(int i=0;i<4;i++)
{
//截取frame
CCSpriteFrame* pFrame =CCSpriteFrame::create("role.png",CCRectMake(i*82,62*2,82,62));
pSpriteArray->addObject(pFrame);
//将精灵添加到场景,默认第一帧图片
if(i==0){
sprite= CCSprite::createWithSpriteFrame(pFrame);
sprite->setPosition(ccp(200,100));
addChild(sprite);
}
}
//从array创建动画
CCAnimation *splitAnimation=CCAnimation::createWithSpriteFrames(pSpriteArray,0.1f);
sprite->runAction(CCRepeatForever::create(CCAnimate::create(splitAnimation)));
}while(0);
bRet=true;
return bRet;
};
制作动态的图片麻烦,就直接贴图了: