Cocos2d-x Learning notes Hello World source Analysis _c language

Source: Internet
Author: User
Tags addchild

First of all, let's say the principle of the game, the game is similar to a movie, the early film is not rely on a picture of the release of it? The picture of what the scene character is in a picture, and then from the first picture to play it. The game is more so, in fact, we play the game to see the pictures are done by the art, we programmers to do is to organize these pictures, such as first to get a background picture, and then in a certain coordinates placed a person's picture, we write a good program to control the image of the moving path, When the machine is running every second to refresh the screen, we can see the characters move up. And the speed of refreshing the page is what we call the frame rate, this in the program we can control. The whole meaning is that the game is just some pictures, and we just control these pictures, let these pictures movement, when the user clicks the picture we do some event response processing and so on, of course, there are some other jobs. Then there are some basic classes in the cocos2d-x, such as the Director class, which is used to control the whole game, just as a true director, with only one director in each game, is a single example design pattern. There are scene classes, layer classes, the most widely used is the wizard class, the scene inside can contain layers, the layer contains the wizard. Let's go through this helloworld scene to get into the Cocos2d-x programming world.

Let's start by running the results and looking at the diagram to illustrate the meaning of the code. The meaning of most of the code is commented, you can see the code.

First, main.cpp.

#include "main.h" #include "AppDelegate.h" #include "CCEGLView.h" USING_NS_CC;
            Uncomment below line, open Debug Console//#define USE_WIN32_CONSOLE int apientry _twinmain (hinstance hinstance, HInstance hPrevInstance, LPTSTR lpcmdline, int ncmdshow) {Unreferenced_parameter (HP
  Revinstance);

Unreferenced_parameter (lpCmdLine);
  #ifdef use_win32_console allocconsole ();
  Freopen ("conin$", "R", stdin);
  Freopen ("conout$", "w", stdout);
Freopen ("conout$", "W", stderr);
	#endif//Create the application instance Appdelegate app; Cceglview is a single design pattern, by calling Sharedopenglview () (as long as you see shared ...).
	On behalf of a single example design pattern) function, obtains the globally unique OpenGL image Engine instance cceglview* Eglview = Cceglview::sharedopenglview (); The following sentence is more important, setframesize (X,y) is to set the size of the game window, by changing the value passed in, you can change the size of the game window, see the window at the top of the line of words, that is, the size of the written window Eglview->setframesize (480

  , 320);

int ret = ccapplication::sharedapplication ()->run ();
#ifdef use_win32_console freeconsole ();
#endif return ret;


 }

The

Appdelegate.cpp the following

#include "cocos2d.h"///want to use the Cocos2d-x engine, you must include this header file #include "CCEGLView.h"//This is the header file of the OpenGL graphics engine #include "AppDelegate.h"/ /This is the lifecycle class header file #include "HelloWorldScene.h"//This is the header file for the HelloWorld scene #include "SimpleAudioEngine.h"//This is the head file of the sound engine/

To use the sound engine, you must use the namespace Cocosdenshion using namespace cocosdenshion;

To use the Cocos2d-x engine, you must use the namespace cocos2d, which is equivalent to the using namespace cocos2d, and you can select it, press F12, and go to its definition using_ns_cc; The following are the constructors and destructors for the Lifecycle Class Appdelegate::appdelegate () {} appdelegate::~appdelegate () {//stop playing the sound at the end of the game lifecycle, know C + +
The base person must know that the end () function is a static function bar simpleaudioengine::end (); //When the game is started, this function is called, so we should look at the initialization of the bool Appdelegate::applicationdidfinishlaunching () {//Director class from this function, which is shared ...
  So it is a single case design pattern ah ccdirector *pdirector = Ccdirector::shareddirector ();

  Pdirector->setopenglview (Cceglview::sharedopenglview ());

  Everyone saw the game in the lower left-hand corner of the number 60, this is the frame rate (is the number of game screen refresh per second), here can be set whether it is displayed in the lower left corner pdirector->setdisplaystats (true); Of course, this is to set the frame rate, on the phone when the frame rate can not be less than 30, otherwise play will be card, the higher the frame rate of course the CPU consumption, the more the cost of electricity, so the frame rate should be reasonable set pdirector->sEtanimationinterval (1.0/60);

  Create a HelloWorld scene, from here you can see scene is a static function bar Ccscene *pscene = Helloworld::scene ();
  The director then invokes the Runwithscene () function to run the HelloWorld scene pdirector->runwithscene (Pscene);
return true; //When we are playing the game suddenly interrupted by other things, such as answering the phone, it will call this function void Appdelegate::applicationdidenterbackground () {//Director call StopAnimation ()
	To stop the playback screen ccdirector::shareddirector ()->stopanimation ();
The sound engine stops playing sound simpleaudioengine::sharedengine ()->pausebackgroundmusic (); This function is called when the event processing is complete, such as a phone call complete void Appdelegate::applicationwillenterforeground () {ccdirector::shareddirector ()-

  >startanimation ();
Simpleaudioengine::sharedengine ()->resumebackgroundmusic ();
 }

The two files in the code we use the template to build success after the basic need not to change, we need to do is to write their own scene class, write before, let's see HelloWorld this scene to achieve it.

Let's see HelloWorld.h first.

#ifndef __helloworld_scene_h__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"

#include " SimpleAudioEngine.h "

//helloworld inherits from Cclayer layer
class Helloworld:public Cocos2d::cclayer
{public
:
  //This is the initialization function of the HelloWorld scene class, is a virtual function
  virtual bool init ();

  This is a static function that can be called directly by a pointer to the class name->scene (), returning a pointer
  static cocos2d::ccscene* scene () of a ccscene scene;

  This is a callback function, which is a response function
  void Menuclosecallback (ccobject* psender) for the click of the End button event;

  The macro can look at his specific implementation by F12, which is actually a new object, and then call its init function (now know when the init function is called), and then return the object's pointer
  create_func (HelloWorld);

#endif//__helloworld_scene_h__

And then the HelloWorld.cpp.

#include "HelloWorldScene.h" using namespace cocos2d;
	ccscene* Helloworld::scene () {ccscene * scene = NULL; This do,while loop will only execute once, why write this, first do not have to do {///first create a ccscene scene, call the CREATE function, in fact, most of the object's creation is to call the CREATE function//created function inside is new An object, and then call the object's init () function, and some work on memory management, first of all, you just have to remember that in C + + we create pointers to objects through new, and are now encapsulated in the CREATE function//maybe sometimes we need to create ()
		To pass something in, but its internal implementation function I said above, with a few parameters. Scene = Ccscene::create ();

    The meaning of the CC_BREAK_IF macro is that if you do not create a successful object scene, you jump out of the Do,while statement cc_break_if (! Scene); We can F12 to create () to see whether the Create_func (HelloWorld) This, that I said the above is right.
    This produces a pointer to the HelloWorld layer.
    HelloWorld *layer = Helloworld::create ();

    CC_BREAK_IF (! Layer);
  Add the HelloWorld layer to the scene scene, add the layer to a scene, add the sprite to the layer, and use this function AddChild () scene->addchild (layer);

  while (0);
Returns the scene return scene containing the HelloWorld layer;
  //Some people may also ask when the Init function was invoked, and I suggest you take a good look at the comment above. BOOL Helloworld::init () {bool BRet = false; Do {//First initialize the init () function of the parent class cc_break_if (!

    Cclayer::init ()); This is a menu item, corresponding to the Close button in the graph, passing in two pictures, toIn the normal state when the button box pressed state button picture//fourth parameter in the Menu_selector is the menu selector, Cocos2d-x also have a lot of selectors, first remember, menuclosecallback corresponding to the callback function, The third argument, this, represents which class's callback function Ccmenuitemimage *pcloseitem = ccmenuitemimage::create ("Closenormal.png", "Closesele
    Cted.png ", this, Menu_selector (Helloworld::menuclosecallback));

    CC_BREAK_IF (! Pcloseitem); Set the coordinates of this button, CCP is also a macro, used to set the coordinates, getwinsize () obtained the size of the screen, return ccsize,width, height is its property pcloseitem->setposition (CCP) (

    Ccdirector::shareddirector ()->getwinsize (). width-20, 20));
    Create a menu where you need to add menu items to the menu in the Cocos2d-x, which is ccmenu, NULL to indicate the end of the menu item.
		ccmenu* Pmenu = ccmenu::create (Pcloseitem, NULL);
    Set the coordinates of this menu Ccpointzero corresponding (0,0) pmenu->setposition (Ccpointzero);

    CC_BREAK_IF (! Pmenu);

    Add a menu to a HelloWorld layer, 1 is the depth, the smaller the number depth, only add to the layer to display This->addchild (Pmenu, 1);
    Create a text, pass in the word, font, size, corresponding to the picture of the HelloWorld cclabelttf* Plabel = cclabelttf::create ("Hello World", "Arial", 24);

    CC_BREAK_IF (! Plabel); Get the size of the screen ccsize size = CCdirector::shareddirector ()->getwinsize ();

    Set coordinates for Plabel plabel->setposition (CCP (SIZE.WIDTH/2, size.height-50));

    Will this text day sword to the layer to show This->addchild (Plabel, 1);
    Adding a sprite to the layer is most commonly used, when the sprite initializes a picture, the resource is resource under the ccsprite* Psprite = ccsprite::create ("Helloworld.png");

    CC_BREAK_IF (! psprite);

    Set the coordinates of this wizard Psprite->setposition (CCP (SIZE.WIDTH/2, SIZE.HEIGHT/2));

    Add the sprite to the layer, the depth is 0 this->addchild (psprite, 0);
  BRet = true;

  while (0);
return bRet; //When the user presses the Close button to invoke the callback function, Ccobject represents the button that is bound to the function and is forced into ccmenuitemimg* void Helloworld::menuclosecallback (
 ccobject* psender) {//Director calls End method ends Game Ccdirector::shareddirector ()->end ();}

There are a few more points in the picture that are shown in the lower left corner, where 3 represents 3 elements, and in this layer we add a sprite, a text, a menu item, so that is 3, 0.000 represents the interval of each frame. The whole implication is that the HelloWorld layer is added to the scene layer, and three sprites are added to the layers, and then the director invokes the Runwithscene () function to run the scene scene.

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.