Cocos2d-x hands-on to achieve the main cycle of the game, cocos2d-x hands-on

Source: Internet
Author: User
Tags integer numbers android games

Cocos2d-x hands-on to achieve the main cycle of the game, cocos2d-x hands-on

Because the Cocos2d-x package is good, so for many new users, they only know the first new scene, add set or genie on the scene, and then run the game with Director runWithScene. If you add an action to an genie, the genie will change. If you add a timer to the set layer, the game will perform the timer. Do you know why?

As a game developer, I think before entering the game industry, we must first understand the "main game loop". Unfortunately, I have only come to study it now. Maybe on the Internet about the Cocos2d-x game main loop explain, but this article, I will teach you how to achieve the main loop of the game.

First, understand the entrance of Cocos2d-x game

Windows application entry is generally in main (), we find the main Cocos2d-x. cpp file, the code inside is very simple:

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();}

Now, we know that the run function in the Application class is the entry. Find the Application. cpp file and capture the most important part of the code of the run function:

while(!glview->windowShouldClose())    {        QueryPerformanceCounter(&nNow);        if (nNow.QuadPart - nLast.QuadPart > _animationInterval.QuadPart)        {            nLast.QuadPart = nNow.QuadPart;                        director->mainLoop();            glview->pollEvents();        }        else        {            Sleep(0);        }    }

No, there is an endless loop here. In a rough view, it is like this: _ animationInterval is the set cycle interval. The difference between the two before and after each time is greater than this interval, execute director> mainLoop () in the main loop. If the interval is smaller than this, the current time is obtained until the interval is greater than this.

This is probably the case. Why is the program always executed? Next, we will implement the following loop by ourselves.




Ii. Windows Performance counters)

In the run function, we find that the main loop of the game is executed when the time difference is greater than the set interval. Where does the time difference come from? This is the stuff: QueryPerformanceCounter, select QueryPerformanceCounter and press F12 to see what is sacred:

//// Performance counter API's//WINBASEAPIBOOLWINAPIQueryPerformanceCounter(    _Out_ LARGE_INTEGER * lpPerformanceCount    );WINBASEAPIBOOLWINAPIQueryPerformanceFrequency(    _Out_ LARGE_INTEGER * lpFrequency    );

That is to say, these two functions are actually from Windows APIs.

QueryPerformanceCounter (): returns the value of the high-precision performance counter. The minimum unit of the exact precision timer of QueryPerformanceCounter is related to the system. Therefore, you must query the system to obtain the frequency of the tick returned by QueryPerformanceCounter.

QueryPerformanceFrequency () provides this frequency value and returns the number of clicks per second.

Calculate the two time intervals, that is, obtain two time intervals using QueryPerformanceCounter (). The two time intervals are divided by the clock frequency, which is the real time difference.


Let's look at the type LAGER_INTEGER:

#if defined(MIDL_PASS)typedef struct _LARGE_INTEGER {#else // MIDL_PASStypedef union _LARGE_INTEGER {    struct {        DWORD LowPart;        LONG HighPart;    } DUMMYSTRUCTNAME;    struct {        DWORD LowPart;        LONG HighPart;    } u;#endif //MIDL_PASS    LONGLONG QuadPart;} LARGE_INTEGER;
LARGE_INTEGER can be an 8-byte long integer (LONGLONG) or a combination of two 4-byte long integer numbers. The specific usage depends on whether the compiler supports 64-bit.




3. Implement the Main Loop

In the past, we were in arrears. With the above knowledge, we can implement it by ourselves.

Use VS2012 to create a win32 console project, open the main. cpp file, and start coding.

Create a MainLoop class first:

Class MainLoop {public: MainLoop (): timeCount (0) {} void setAnimationInterval (double interval); void run (); private: LARGE_INTEGER _ animationInteval; unsigned timeCount ;}; void MainLoop: setAnimationInterval (double interval) {LARGE_INTEGER nFreq; QueryPerformanceFrequency (& nFreq); _ animationInteval. quadPart = (LONGLONG) (interval * nFreq. quadPart);} void MainLoop: run () {LARGE_INTEGER nFreq; LARGE_INTEGER nBeginTime; LARGE_INTEGER nEndTime; QueryPerformanceFrequency (& nFreq ); // obtain the clock frequency of the machine's Internal timer QueryPerformanceCounter (& nBeginTime); // obtain the first count while (1) // an endless loop {QueryPerformanceCounter (& nEndTime ); // obtain the second count if (nEndTime. quadPart-nBeginTime. quadPart> _ animationInteval. quadPart) // If the difference between two counts is greater than the specified interval, execute {timeCount ++; printf ("% d \ n", timeCount); nBeginTime = nEndTime ;}}}

You can set the time interval for this class. When the difference between the last two times is greater than this interval, A timeCount is output, and timeCount is the counter.


int _tmain(int argc, _TCHAR* argv[]){MainLoop loop;loop.setAnimationInterval(1);loop.run();system("pause");return 0;}
In the main function, we first set the interval to 1 second to start running. Then we can see that the console will output the counter every 1 second:



This is the loop we want, think about, the smaller the time interval, the more fast the counter is added, when the time interval is 1/60, just like the Cocos2d-x.

Go back and check out the Application code. However, what is executed in the Application is not the counter overlay, but the director-> mainLoop (), which is also called the main loop of the game.


The analysis of the main loop of the game is here. There are a lot of the same articles on the Internet. ctrl + c and ctrl + v are too simple, I hope this article is different from other Cocos2d-x game Main Loop will help you.


To write android games with cocos2d-x, you must go back to c ++

Cocos2d-x itself is C ++ written ah, so must be c ++, in the windows platform with cocos2d-x to write android Games first with visual stdio programming cocos2d-x game, and then run successfully, then, use eclipse to add the generated program framework. In this way, you can generate an android game.

C ++ COCOS2D-X development of computer games, can achieve serial communication?

Cocos2d-x can give you realize rich animation effect, serial communication you use serial communication knowledge to solve it, your project contains cocos2d-x class library, you can use previous knowledge for serial communication. These two do not interfere with each other.

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.