4, COCOS2DX 3.0 Three, find a small game development Hello World Analysis

Source: Internet
Author: User
Tags addchild

respect the work of the developer. When reproduced, please be sure to indicate the source: http://blog.csdn.net/haomengzhu/article/details/27186557

Hello World Analysis
Open the new "findmistress" project to see that the project file is made up of multiple code files and directories. The code files for Hello world are directlystored in the project directory. Let's take a look at the file composition of the project in detail below.

1. "Resource" This directory is primarily used to store resource files such as images, audio, and configuration needed in the game. For ease of management. The ability to create subdirectories in them.

Under different flat tables, the definition of the file path is inconsistent, but the actual interface is similar.

Cocos2d-x has blocked these differences for us, with the "resource" folderbe able to feel the folder when the game executes.
Do you remember the game we played in the last section? The Cocos2d-x logo shown in the game is placed below this directory. In addition, this catalogue also guaranteesSave the font for the lower-left FPS of the game and exit the picture on the game button.
2. "Classes" and "Proj.win32" directoriesThese two directories are used to place the game header files and source files. Can see that the project template for us to join the three files are "Main.h", "Main.cpp"and "resource.h", they are platform-related program files that are proprietary to Windows. usually. Program entry and resource file management under different platforms aredifferent, but the cocos2d-x template has been basically for us to deal with these details, do not need to change them.


3. "AppDelegate.h" and "AppDelegate.cpp" filesThese two files are common entry files for cocos2d-x games. Similar to the file where the main function in Windows project is typically located. Readers who have been exposed to iOS development shouldthe two files have a familiar name, in fact Appdelegate is the program's entry file in IOS project. In introducing the history of the engine, I have mentionedever been there.  Cocos2d-x comes from Cocos2d-iphone, so whether it's a code style or a file structure. Many aspects of the cocos2d-iphone are followed by the use of the habit. later in this article, we will describe the code style and file structure of cocos2d-x.
open "AppDelegate.cpp". We are able to see the code that has been actively added to this file, which implements the Appdelegate class. Appdelegate controls the game.'s life cycle. With the exception of constructors and destructors, there are 3 common methods, which we will describe individually.


bool Applicationdidfinishlaunching (). This method is called after the application starts. The default implementation already includes the necessary preparation after the game starts:
//Initialize the game engine controller director to start the game engine//Initialize directorAuto Director = Director::getinstance ();Auto Glview = Director->getopenglview ();if (!glview) {Glview = glview::create ("My Game");Director->setopenglview (glview);    }
//enable FPS displayDirector->setdisplaystats (true);
//Set drawing intervalDirector->setanimationinterval (1.0/60); //Create a scene. It ' s an Autorelease objectAuto scene = Helloworld::createscene ();
//Rundirector->runwithscene (scene);
return true;
This code first initializes the engine as necessary, and then turns on the FPS display. FPS is the frame rate per second, which is how many times the screen is redrawn per second. Enabled thewhen FPS is displayed, the current FPS is displayed in the lower-left corner of the game. Usually in the game development phase, we will enable FPS display, so that you can easily determine the game operationThe line is smooth.


the next step is to set the drawing interval. Drawing interval refers to the time interval of two draws. So the countdown to the drawing interval is the maximum FPS. for mobile devices. We usually limit FPS to an appropriate range. Low redraw times per second can cause the animation to show a lag, and increasing the number of redraws per second will result in a significant increase in the amount of device computation. resulting in higher energy consumption.

The human eye's refresh rate is about 60 times per second. So limiting the FPS to 60 is a more reasonable setting, and the Cocos2d-x will set the drawing interval to 1/60 seconds.

here. We're done with the engine initialization, and then we'll start the engine.
Finally, and the most critical step, is to create the Hello world scene and assign the Director to execute the scenario. For game developers, we
void applicationdidenterbackground (). This method is called when the application is going to enter the background. In detail, when the user switches the program to sound.

The

Action-intensive game should also normally be paused at this time. So that players can leave the game temporarily without significant loss.
void applicationwillenterforeground ().

This method appears in pairs with Applicationdidenterbackground (), and the application returns to the foreground   is called. relatively to. We usually continue to play the music we just paused here, show the game pause menu, and so on.
" HelloWorldScene.h "and" HelloWorldScene.cpp "files. These two files define the default game scenario in the Hello World project.
cocos2d to another component, form hierarchical relationships, such as the ability to include multiple layers in a scene. Multiple sprites can be included in the layer. In the article, we will specifically explain cocos2d The concept of game elements. This will not specify how to create the Hello world scenario.


a HelloWorld class is defined in Helloworldscene. This class inherits from Cocos2d::layer. So HelloWorld itself is a layer. The HelloWorld class includesa static function and two instance methods, here we look at the more important two members.
static cocos2d::scene* Createscene (). In cocos2d, it is a common technique to set up a static function that creates a scene under a layer. We are HelloWorldlayer to write a subclass of layer, in the subclass to add a variety of sprites or logic processing code. However, our Hello world scene is very simple. includes only one layer, no matter what else needs to be dealt with. Therefore, in addition to creating a subclass of Scene, we are able to use static functions directlynumber to create an empty scene. Then place the layer in the scene. This is also very handy, demonstrating sample code such as the following:
//' scene ' is an Autorelease objectAuto scene = Scene::create ();    //' layer ' is an Autorelease objectAuto layer = Helloworld::create ();
//Add layer as a child to scenescene->addchild (layer);
in this code, you first create an empty scene with the Scene::create method, and then use the Hello World::create method to create a HelloWorldlayer, and finally calls the scene object's AddChild method to add the created layer to the scene.


This is the first time we have seen the AddChild method, which can put a game element into one element.

just put a game element into its He has presented the elements of the game that it will only present. in This example, we put the HelloWorld layer into an empty scene created above , and in the AddDelegate described earlier, we have the Director execute the scene, so The HelloWorld layer will be displayed on the screen.
BOOL Init ().

Initialize the HelloWorld class with the relevant code such as the following://(1) Initialize the parent classif (! Layer::init ())    {return false;    }
//(2) Create a menu and join to the layerAuto Closeitem = menuitemimage::create ("Closenormal.png","Closeselected.png",Cc_callback_1 (Helloworld::menuclosecallback, this));    closeitem->setposition (Point (origin.x + visiblesize.width-closeitem->getcontentsize (). WIDTH/2,ORIGIN.Y + closeitem->getcontentsize (). height/2));
//Create menu, it ' s an Autorelease objectAuto Menu = Menu::create (Closeitem, NULL);menu->setposition (Point::zero);this->addchild (menu, 1);
//(3) Create a "Hello World" tag and add it to the layerAuto label = labelttf::create ("Hello World", "Arial");    //Position the label on the center of thelabel->setposition (Point (origin.x + VISIBLESIZE.WIDTH/2,ORIGIN.Y + visiblesize.height-label->getcontentsize (). height));
//Add the label as a child to this layerthis->addchild (label, 1);
//(4) Create a sprite that shows "Helloworld.png" and add it to the layer//Add "HelloWorld" splash screen "Auto Sprite = sprite::create ("Helloworld.png");
//Position the sprite on the center of thesprite->setposition (Point (VISIBLESIZE.WIDTH/2 + origin.x, VISIBLESIZE.HEIGHT/2 + origin.y));
//Add the sprite as a child to this layerThis->addchild (Sprite, 0);
This code can be easily divided into 4 parts.

The Init method of the parent class is called to initialize the initial initialization.

creates a menu that closes the program and joins it to the layer. Here, we met AddChild (node* child,int zOrder). With the previous AddChild method came out a number of zOrder, which refers to the child's z-axis order. That is, the order of the display, the greater the value. Indicates that the position displayed is more forward. The SetPosition method is used to set the location of the game element.
About the menu and the text labels mentioned below. We will also cover this in a later chapter.

Create a text label and add it to the layer to display the content "Hello world". Create a sprite with "helloworld.png" and add it to the layer. The last program returns TRUE, indicating that the initialization was successful.

Readers may have doubts at this point. Why do we initialize a class in an instance method without initializing it in the constructor?
In C + +, the general habit is to construct initializes the class in the build function. Since the source of the cocos2d-x is however special. That's why you don't have a C + + programming style.

As for the programming style, we will discuss it in a later article.


Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

4, COCOS2DX 3.0 Three, find a small game development Hello World Analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.