Cocos2d-x (i): Understanding the entire game framework from the Hello World example

Source: Internet
Author: User
Tags addchild
<span style= "font-family: Microsoft Ya-hei; Background-color:rgb (255, 255, 255); > First find main.cpp, program to enter </span>
A game that corresponds to a application,application responsibility is to manage the game lifecycle and set the default window to obtain platform and localized information. Application::getinstance ()->run () is the portal for the entire application.
int Apientry _tWinMain (hinstance hinstance,
                       hinstance hprevinstance,
                       LPTSTR lpcmdline,
                       int ncmdshow)
{
    unreferenced_parameter (hprevinstance);
    Unreferenced_parameter (lpcmdline);

    Create the application instance
    appdelegate app;
    Return Application::getinstance ()->run ();
}

Application usually does not create a Application object directly, but instead creates a appliction subclass: Appdelegate can see it in the game entry application::getinstance ()->run ()
    if (!applicationdidfinishlaunching ())
    {return
        0;
    }

In Applicationdidfinishlaunching, first initialize a Director and create an OpenGL es window for Director, and then create the first scene. General settings such as resolution, frame rate, resource search directory are all completed in applicationdidfinishlaunching.
A basic application starts with the initial chemical as follows:
BOOL Appdelegate::applicationdidfinishlaunching () {
    Auto Director = Director::getinstance ();
    Auto Glview = Director->getopenglview ();
    if (!glview) {
        Glview = glviewimpl::create ("Cpp Empty Test");
        Director->setopenglview (Glview);
    }

    Director->setanimationinterval (1.0/60);

    Auto scene = Helloworld::scene ();

    Director->runwithscene (scene);

    return true;
}

Now the operating system basically supports multitasking, when the player leaves the game, should suspend the game:
void Appdelegate::applicationdidenterbackground () {
    director::getinstance ()->stopanimation ();

}

When the player returns to the game, the game should be restored:
void Appdelegate::applicationwillenterforeground () {
    director::getinstance ()->startanimation ();

    If use Simpleaudioengine, it must resume here
    //Simpleaudioengine::sharedengine ()->resumebackgroundmusic ();
}

The frame rate Director->setanimationinterval (1.0/60) is set in the applicationdidfinishlaunching. The frame rate determines how the game cycle is updated at what intervals. Application::Run drive the game cycle, according to the frame rate set for the game's Cycle logic update, the following is the implementation of Application::Run
int Application::Run () {Pvrframeenablecontrolwindow (false);
    Main message Loop:large_integer nlast;

    Large_integer Nnow;

    QueryPerformanceCounter (&nlast);

    Initglcontextattrs ();
    Initialize instance and cocos2d.
    if (!applicationdidfinishlaunching ()) {return 0;
    Auto director = Director::getinstance ();

    Auto Glview = Director->getopenglview ();

    Retain Glview to avoid Glview being released in the while Loop Glview->retain ();
        while (!glview->windowshouldclose ()) {QueryPerformanceCounter (&nnow); if (Nnow.quadpart-nlast.quadpart > _animationinterval.quadpart) {nlast.quadpart = Nnow.quadpart
            
            -(nnow.quadpart% _animationinterval.quadpart);
            Director->mainloop ();
        Glview->pollevents ();
        else {sleep (1); }//Director should still do a cleanup if the window was closed manually.
        if (Glview->isopenglready ()) {director->end ();
        Director->mainloop ();
    Director = NULLPTR;
    } glview->release ();
return true; }

Mainloop defines a game loop for all events and Content Application::Run () after a loop, hibernate until the next update is idle, until the next cycle is updated.

In the applicationdidfinishlaunching, you can see
    Auto scene = Helloworld::scene ();
    Director->runwithscene (Scene);
Auto scene = Helloworld::scene (); Creates a scene
scene* Helloworld::scene ()
{
    //' Scene ' is a Autorelease object
    auto Scene = Scene::create ();
    
    ' Layer ' is a Autorelease object
    HelloWorld *layer = Helloworld::create ();

    Add layer as a child to scene
    Scene->addchild (layer);

    Return the scene return
    scene;
}

As you can see, creating a class calls the CREATE function, why not direct new Scene (), we open the CREATE function
scene* scene::create ()
{
    Scene *ret = new (Std::nothrow) Scene ();
    if (ret && ret->init ())
    {
        ret->autorelease ();
        return ret;
    }
    else
    {
        cc_safe_delete (ret);
        Return nullptr
    }
}

You can see that in the CREATE function, first the new object is called, then the object's Init method is invoked, and the modified object is added to the Cocos2d-x memory management and set to automatic release. In Cocos2d-x, objects are inherited from the ref base class, and the ref base class is primarily responsible for referencing technical management of objects. Declare an object pointer as a smart pointer with the Autorelease () method, but the smart pointers are not associated with an automatic variable alone, but are all joined in a autoreleasepool. Add the objects in the Autoreleasepool at the end of each frame to clean up. So, in Cocos2d-x, the lifecycle of a smart pointer ends at the end of the current frame, starting with the creation.
The initialization of a class is generally done in Init in Helloworld::init, and the work done has created a menu, a character tag and an elf. Director::getinstance ()->getvisiblesize () Gets the window size director::getinstance ()->getvisibleorigin () Gets the game coordinates, which defaults to the lower left corner ( 0,0) to create the code for the menu:
Auto Closeitem = menuitemimage::create (
                                        "Closenormal.png",
                                        "Closeselected.png",
                                        cc_callback_1 ( Helloworld::menuclosecallback,this));
    
    Closeitem->setposition (Origin + VEC2 (visiblesize)-VEC2 (Closeitem->getcontentsize ()/2));

    Create menu, it ' s an Autorelease object
    auto menu = Menu::create (Closeitem, nullptr);
    Menu->setposition (Vec2::zero);
    This->addchild (menu, 1);

Here is the use of pictures to create a menu, the default when the button picture is closenormal.png selected for Closeselected.png, and added a listener, the menu is clicked when the Menuclosecallback function is called. Using SetPosition to set the menu position, This->addchild (menu, 1) to place the menus into the layer of the scene, 1 for the priority of the display to create character labels and sprites (background pictures) are all using a similar method, first invoking create creation, Then use the setposition to set the position and add the layer through the addchild. After the initialization of the scene, Director->runwithscene (scene); Run the scene. The first scene of the game run using the Runwithscene method after the scene is run using Director->replacescene (Newscene) replaces the current scene. Program Run Effect:

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.