本教程由落羽原創,歡迎轉載,轉載請註明地址http://blog.csdn.net/cqjianx/article/category/2407957
1.建工程
遊戲最重要的就是動畫,作爲本系列教程的第一篇,動畫最合適了。這一節主要包含helloworld程序的講解以及一個簡單動畫播放。首先新建一個cocos2dx helloworld工程,建好後看起來是這樣。
運行下, 如果沒問題了運行起來是這樣
2.修改AppDelegate.cpp
接下來我們對程序進行下修改,以便於我們後續的開發。
打開AppDelegate.cpp,修改程序初始化函數
bool AppDelegate::applicationDidFinishLaunching() {
// initialize director
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
if(!glview) {
glview = GLView::create("My Game");
director->setOpenGLView(glview);
}
// turn on display FPS
director->setDisplayStats(false); //不顯示FPS
glview->setDesignResolutionSize(1280, 800, ResolutionPolicy::EXACT_FIT); //設置屏幕適配尺寸和策略
// set FPS. the default value is 1.0/60 if you don't call this
director->setAnimationInterval(1.0 / 60);
// create a scene. it's an autorelease object
auto scene = HelloWorld::createScene();
// run
director->runWithScene(scene);
return true;
}
做的改動就是把顯示FPS去掉,設置屏幕適配尺寸爲1280*800,適配策略爲EXACT_FIT,
爲什麼要設置成1280*800? 因爲以後教程的動畫都是基於1280*800的屏幕來畫的,所以這裏先設置好,方便接下來的開發。至於適配策略,落羽這裏簡單講下,不再深入講解,
主要有三種,分別是
EXACT_FIT:充滿整個屏幕,遊戲畫面有可能變形。
NO_BORDER:按比例拉伸,不留黑邊,遊戲畫面有可能超出屏幕外。
SHOW_ALL:按比例拉伸,在屏幕內顯示整個遊戲畫面,有可能留下黑邊。
3.修改helloword.cpp加入動畫
打開helloword.cpp修改初始化函數。
把默認添加的label和背景去掉,添加我們自己的背景, 加載動畫創建精靈,播放動畫。
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it.
// add a "close" icon to exit the progress. it's an autorelease object
auto closeItem = MenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
origin.y + closeItem->getContentSize().height/2));
// create menu, it's an autorelease object
auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);
//my code
auto *background = Sprite::create("background.png"); //添加背景
background->setPosition(Point(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
this->addChild(background);
Vector<SpriteFrame*> frameVector; //動畫圖片容器
char str[30];
for(int i = 1; i <= 8; ++i) //加載圖片
{
sprintf(str, "player1_brother_move_%02d.png", i);
frameVector.pushBack(SpriteFrame::create(str, Rect(0, 0, 600, 400)));
}
auto *animation = Animation::createWithSpriteFrames(frameVector, 0.1);
auto *animate = Animate::create(animation);
auto *action = RepeatForever::create(animate); //創建無限循環動畫
auto sprite = Sprite::create();
sprite->setPosition(Point(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
sprite->runAction(action);
this->addChild(sprite);
return true;
}
當然創建動畫有好幾種方式,落羽這裏只用了一種方式,以後我們會用到其他的方式,這部分內容比較簡單,創建下精靈,播放動畫,添加子節點,就好了。最後的效果如下。
圖片都是落羽自己畫的哦,哈哈