Cocos2d x learning notes for Hello World source analysis

  • 2020-04-02 02:42:00
  • OfStack

First of all, let's talk about the principle of the game. The game is similar to a movie. The scene of what the drawing of the characters on a picture, and then from the first picture began to play. Game even more so, the images we see games are actually artists make, our programmers to do is to organize the images, such as to get a background image, and then placed at a certain coordinates a images of the characters, we write a program, to control the movement of the image path, while waiting for the machine running to refresh every 1 second picture, we see the character move up. And the speed of refreshing the page is what we call the frame rate, which we can control in the program. The whole idea is that the game is just a bunch of pictures, and we just control the pictures, make the pictures move, do some event response processing when the user clicks on the picture, and of course some other things. Then there are some basic classes in cocos2d-x, such as the director class, which is used to control the whole game. Just like the real director, there is only one director in each game, which is a singleton design pattern. There are scene class, layer class, the most widely used is the Sprite class, scene inside can contain layers, layer contains Sprite. Let's use this helloworld scene to enter the programming world of cocos2d-x.

Let's run the results and look at the diagram to illustrate the code. Most of the code is annotated, so you can look at the code.

The first is the 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(hPrevInstance);
  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 singleton design pattern, by calling sharedOpenGLView(). Represents a singleton design pattern) function to obtain globally unique opengl image engine instance
  CCEGLView* eglView = CCEGLView::sharedOpenGLView();
	//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 line at the top of the window, is the size of the window
  eglView->setFrameSize(480, 320);

  int ret = CCApplication::sharedApplication()->run();

#ifdef USE_WIN32_CONSOLE
  FreeConsole();
#endif

  return ret;
}


Appdelegate. CPP is as follows


#include "cocos2d.h"	//To use the cocos2d-x engine, include this header file
#include "CCEGLView.h"	//This is the header file for the opengl graphics engine
#include "AppDelegate.h"	//This is the life cycle class header file
#include "HelloWorldScene.h"	//This is the header file for the HelloWorld scenario
#include "SimpleAudioEngine.h"	//This is the header file for 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, this macro definition is equivalent to using namespace cocos2d, you can select it, press f12, go to its definition
USING_NS_CC;

//The following two are the constructor and destructor of the life cycle class
AppDelegate::AppDelegate()
{
}

AppDelegate::~AppDelegate()
{
	//Stop playing sound at the end of the game life cycle. Anyone who knows the basics of c++ must know that the end() function is static
  SimpleAudioEngine::end();
}

//This function is called when the game starts, so we should start with this function
bool AppDelegate::applicationDidFinishLaunching()
{
  //Director class initialization, again Shared... So it's a singleton design pattern again
  CCDirector *pDirector = CCDirector::sharedDirector();
  pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());

  //Did you see the number 60 in the bottom left corner of the game? This is the frame rate (the number of screen refreshes per second)
  pDirector->setDisplayStats(true);

  //Of course, here is to set the frame rate, on the phone when the frame rate should not be less than 30, otherwise the game will be stuck, the higher the frame rate of course, the more CPU consumption, also more power consumption, so the frame rate should be set reasonably
  pDirector->setAnimationInterval(1.0 / 60);

  //Create a helloworld scene, and from there you can see that the scene is a static function
  CCScene *pScene = HelloWorld::scene();

  //The director then calls the runWithScene() function to run the helloworld scene
  pDirector->runWithScene(pScene);
  return true;
}

//This function is called when we are playing a game and are suddenly interrupted by something else, such as answering a phone call
void AppDelegate::applicationDidEnterBackground()
{
	//The director calls stopAnimation() to stop the picture
  CCDirector::sharedDirector()->stopAnimation();
	//The sound engine stops playing sound
  SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
}

//This function is called when the event processing is complete, such as when the call is answered
void AppDelegate::applicationWillEnterForeground()
{
  CCDirector::sharedDirector()->startAnimation();

  SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
}

The code in the above two files is basically unchanged after we successfully generate it with the template. All we need to do is write our own scenario class. Before writing, let's see the implementation of the scenario of HelloWorld.

Start with the HelloWorld. H


#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"

#include "SimpleAudioEngine.h"

//HelloWorld inherited from the CCLayer layer
class HelloWorld : public cocos2d::CCLayer
{
public:
  //This is the initialization function of the HelloWorld scenario class, which is a virtual function
  virtual bool init();

  //This is a static function, and you can do it by pointing to the class name. Scene () is called directly, returning a pointer to the CCScene scene
  static cocos2d::CCScene* scene();

  //This is a callback function that is a response to the end button event
  void menuCloseCallback(CCObject* pSender);

  //This macro can be implemented by f12, which is a new object, and then call its init function (now you know when the init function is called), and then return a pointer to that object
  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 only executes once, why do I write it like that? Forget it
  do
  {
    //First, create a scene of CCScene, which calls the create function. In fact, most objects are created by calling the create function
		//Inside of this create function is a new object, and then it calls the init() function of the object, and some of the memory management stuff, forget that, you just have to remember that in c++ we created a pointer to an object through new, and now it's encapsulated in the create function
    //There may be times when we need to pass something in to create(), but the internal implementation of this function, as I said, just takes a few arguments
		scene = CCScene::create();
		//The meaning of the CC_BREAK_IF macro is to break out of the do,while statement if the successful object scene is not created
    CC_BREAK_IF(! scene);

    //You can do create()f12 and see if you're at CREATE_FUNC(HelloWorld), which means I'm right. This generates a pointer to the helloworld layer.
    HelloWorld *layer = HelloWorld::create();
    CC_BREAK_IF(! layer);

    //Add the helloworld layer to the scene, add the layer to the scene, add the sprit to the scene and so on
    scene->addChild(layer);
  } while (0);

  //Returns the scenario that contains the layer helloworld
  return scene;
}

//Some of you might also ask when was the init function called, and I suggest you take a good look at the comment up here, okay
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 picture, passing in two pictures, corresponding to the button box in the normal state of the button pressed state of the picture
		//The fourth parameter, menu_selector, is the menu selector, and cocos2d-x has a bunch of selectors, so remember, menuCloseCallback corresponds to that callback function, and the third parameter, this, is the callback function of that class
    CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
      "CloseNormal.png",
      "CloseSelected.png",
      this,
      menu_selector(HelloWorld::menuCloseCallback));
    CC_BREAK_IF(! pCloseItem);

    //Set the coordinates of this button, CCP is also a macro, to set the coordinates, getWinSize() to get the size of the screen, return CCSize, width, height are its properties
    pCloseItem->setPosition(ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20));

    //Create a menu. In cocos2d-x, you need to add the menu item to the menu, that is, to the CCMenu. NULL indicates the end of the menu item.
    CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
		//Set the coordinates of CCPointZero for this menu to correspond to (0,0)
    pMenu->setPosition(CCPointZero);
    CC_BREAK_IF(! pMenu);

    //Add the menu to the layer of HelloWorld. 1 represents the depth. The smaller the number, the deeper the depth
    this->addChild(pMenu, 1);

    //Create a text, pass in the word, font, size to be displayed, corresponding to the helloworld on the picture
    CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Arial", 24);
    CC_BREAK_IF(! pLabel);

    //Get the screen size
    CCSize size = CCDirector::sharedDirector()->getWinSize();
		//Set the coordinates for pLabel
    pLabel->setPosition(ccp(size.width / 2, size.height - 50));

    //Put the text on the layer to display it
    this->addChild(pLabel, 1);

    //It is most commonly used to add a Sprite to the layer. When the Sprite initializes, an image is passed in, and the resource is under resource
    CCSprite* pSprite = CCSprite::create("HelloWorld.png");
    CC_BREAK_IF(! pSprite);

    //Set the coordinates of the Sprite
    pSprite->setPosition(ccp(size.width/2, size.height/2));

    //Add the Sprite to the layer with a depth of 0
    this->addChild(pSprite, 0);

    bRet = true;
  } while (0);

  return bRet;
}

//This callback function is called when the user presses the close button. CCObject represents the button that is bound to this function and is forced to be converted to CCMenuItemImg* when used
void HelloWorld::menuCloseCallback(CCObject* pSender)
{
  //The director calls the end method to end the game
  CCDirector::sharedDirector()->end();
}

There are a few things to say about the image that are displayed. The 3 in the bottom left corner represents 3 elements. On this layer, we added a Sprite, a text, and a menu item, so it's 3,0.000 for each frame. The whole idea is to add the helloworld layer to the scene, add three sprites to the layer, and then the director calls the runWithScene() function to run the scene.


Related articles: