原理:
Cocos2D中有个导演控制整个游戏流程,导演将场景添加到屏幕上,场景中有各种各样的演员。
AppDelegate.cpp
bool AppDelegate::applicationDidFinishLaunching(){ // 初始化导演 CCDirector* pDirector = CCDirector::sharedDirector(); // 使用绑定opengles窗口 CCEGLView* pEGLView = CCEGLView::sharedOpenGLView(); pDirector->setOpenGLView(pEGLView); // 打开左下角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 = GameScene::scene(); // 运行此场景 pDirector->runWithScene(pScene); return true;}
上边的代码添加了一个场景GameScence,下面看看具体实现:
GameScence.h
#pragma once#include "cocos2d.h" USING_NS_CC; class GameScene : public CCLayer{public: GameScene(void); ~GameScene(void); //重写init()方法 virtual bool init(); //必须重写scene方法 static CCScene* scene(); //相当于create函数,重写了CCLayer里的create函数 CREATE_FUNC(GameScene);};
GameScence.cpp
#include "GameScene.h" GameScene::GameScene(void){}GameScene::~GameScene(void){} CCScene* GameScene::scene(){ CCScene* scene =CCScene::create(); GameScene* gameScene = GameScene::create(); scene->addChild(gameScene); return scene;} bool GameScene::init(){ if(!CCLayer::init()) { return false; } //获取屏幕大小 CCSize size = CCDirector::sharedDirector()->getWinSize(); //从图片创建一个精灵 CCSprite* sprite = CCSprite::create("bg.png"); //设置精灵在场景中的位置 sprite->setPosition(ccp(size.width / 2, size.height / 2)); //添加精娄到场景中 this->addChild(sprite, 0); return true;}
代码中有注释,就不在重复叙述了,下面是效果图:
怎么让其显示一个动态的精灵呢,下面是修改后的init()
GameScene.cpp
bool GameScene::init(){ if(!CCLayer::init()) { return false; } //获取屏幕大小 CCSize size = CCDirector::sharedDirector()->getWinSize(); //从图片创建一个精灵 CCSprite* map = CCSprite::create("bg.png"); //设置精灵在场景中的位置 map->setPosition(ccp(size.width / 2, size.height / 2)); //添加精娄到场景中 this->addChild(map, 0); CCSprite* sprite; CCArray* spriteArray = CCArray::createWithCapacity(4); int i; for(i = 0; i < 4; i++) { //截取图片部分 CCSpriteFrame* spriteFrame = CCSpriteFrame::create("lubi.png", CCRectMake(i * 80, 80 * 2, 80, 80)); spriteArray->addObject(spriteFrame); //精精灵添加到场景中,默认第一帧图片 if(i == 0){ sprite = CCSprite::createWithSpriteFrame(spriteFrame); sprite->setPosition(ccp(size.width / 2 - sprite->getContentSize().width, size.height / 2 + sprite->getContentSize().height)); this->addChild(sprite); } } //创建动画 CCAnimation* spriteAnimation = CCAnimation::createWithSpriteFrames(spriteArray, 0.2f); sprite->runAction(CCRepeatForever::create(CCAnimate::create(spriteAnimation))); return true;}
制作动态的图片麻烦,就直接贴图了: