cocos2d新建项目详细解释

win32

main.h

#ifndef __MAIN_H__
#define __MAIN_H__
// Exclude rarely-used stuff from Windows headers
//从Windows头文件中排除很少使用的内容
#define WIN32_LEAN_AND_MEAN             

// Windows Header Files:
//Windows头文件:
#include <windows.h>
#include <tchar.h>

// C RunTime Header Files
//C运行时头文件
#include "CCStdC.h"

#endif    // __MAIN_H__

#include "CCStdC.h"

Cocos2d-x中,#include "CCStdC.h" 这个头文件包含了一些C语言标准库的声明。

CCStdC.h提供了对一些常用C语言标准库函数和宏的访问。其中包含:

  • 标准输入输出函数:printfscanf
  • 字符串操作函数:strcpystrcmp
  • 数学函数:sincos
  • 通用工具宏:NULLMAX
  • 标准数据类型:size_t
  • 断言宏:assert

包含这个头文件后,可以不用再包含像<string.h><math.h>等C语言标准头文件,就可以直接使用这些标准C函数和宏。

这样可以简化Cocos2d-x代码中的包含头文件语句。通过只包含CCStdC.h一个头文件,就可以访问到常用的C语言标准库。

总之,在Cocos2d-x代码中,包含CCStdC.h是一个简单方便访问C语言标准库函数和宏的方式。

main.cpp

#include "main.h"
#include "AppDelegate.h"
#include "cocos2d.h"

//使用cocos2d命名空间
//宏定义 using namespace cocos2d
USING_NS_CC;

//_tWinMain是Windows平台下的入口函数形式
//hInstance是程序本身的实例句柄
//hPrevInstance是上一个实例句柄,这里不需要用到
//lpCmdLine是命令行参数,这里也不需要用到
//nCmdShow是显示参数
int APIENTRY _tWinMain(HINSTANCE hInstance,
                       HINSTANCE hPrevInstance,
                       LPTSTR    lpCmdLine,
                       int       nCmdShow)
{
	//UNREFERENCED_PARAMETER宏用于屏蔽不需要的形参,避免编译器警告。
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);

	//cocos2d调出控制台【自己添加】
	AllocConsole();
	freopen("CONIN$", "r+t", stdin);
	freopen("CONOUT$", "w", stdout);
	freopen("CONOUT$", "w", stderr);

    // create the application instance
	//创建一个应用实例(Delegate委托)
    AppDelegate app;

	//调用Application的静态getInstance方法获取单例对象
	//通过Application单例的run方法启动Cocos2d-x游戏流程
	//run方法会执行AppDelegate对象的应用回调
	//整个流程实现了使用AppDelegate启动Cocos2d-x应用
    return Application::getInstance()->run();
}

其中:

//cocos2d调出控制台【自己添加】
	AllocConsole();
	freopen("CONIN$", "r+t", stdin);
	freopen("CONOUT$", "w", stdout);
	freopen("CONOUT$", "w", stderr);

Cocos2d-x中,这几行代码的作用是:

打开控制台窗口,并将输入输出流重定向到控制台。

具体分析:

  1. AllocConsole() 函数用于打开一个控制台窗口。
  2. freopen() 函数可以重定向指定的文件流。
  3. "CONIN$" 表示标准输入流stdin
  4. "CONOUT$" 表示标准输出流stdout和标准错误流stderr
  5. 这样就可以在控制台窗口中进行输入和输出。
  6. Cocos2d-x中,可以使用这些代码在游戏运行时打开一个控制台。
  7. 然后在控制台中打印日志或者输入测试命令。

所以这几行代码打开了控制台窗口,并将输入输出流连接到了控制台,使得我们可以在Cocos游戏运行时与控制台进行交互。

这在Cocos2d-x中可以用于打印调试信息或提供交互式的命令行界面。

AppDelegate.h

#ifndef  _APP_DELEGATE_H_
#define  _APP_DELEGATE_H_

#include "cocos2d.h"

/**
@brief    The cocos2d Application.
		  cocos2d应用程序
The reason for implement as private inheritance is to hide some interface call by Director.
实现为私有继承的原因是为了隐藏Director的一些接口调用。
*/
class  AppDelegate : private cocos2d::Application
{
public:
    AppDelegate();
	//虚析构函数(类中有虚函数,并且作为基类),动态多态使用时导致派生类的析构函数没有被调用                                                    
    virtual ~AppDelegate();

	//初始化 视图的内容
    virtual void initGLContextAttrs();

    /**
    @brief    Implement Director and Scene init code here.
    @return true    Initialize success, app continue.
    @return false   Initialize failed, app terminate.
    */
	//应用程序 已经完成 加载
    virtual bool applicationDidFinishLaunching();

    /**
    @brief  The function be called when the application enter background
    @param  the pointer of the application
    */
	//应用程序 已经进入 后台
	//完全定义才能调用
    virtual void applicationDidEnterBackground();

    /**
    @brief  The function be called when the application enter foreground
    @param  the pointer of the application
    */
	//应用程序 即将进入 前台
	//即将进入前台就会调用
    virtual void applicationWillEnterForeground();
};

#endif // _APP_DELEGATE_H_

AppDelegate.cpp

#include "AppDelegate.h"
#include "HelloWorldScene.h"

//使用cocos2d命名空间
USING_NS_CC;

//设置分辨率,一般来书用第一行的
static cocos2d::Size designResolutionSize = cocos2d::Size(480, 320);
static cocos2d::Size smallResolutionSize = cocos2d::Size(480, 320);
static cocos2d::Size mediumResolutionSize = cocos2d::Size(1024, 768);
static cocos2d::Size largeResolutionSize = cocos2d::Size(2048, 1536);

AppDelegate::AppDelegate() {

}

AppDelegate::~AppDelegate() 
{
}

//if you want a different context,just modify the value of glContextAttrs
//如果你想要一个不同的上下文,只需修改glContextAttrs的值
//it will takes effect on all platforms
//将在所有平台生效
void AppDelegate::initGLContextAttrs()
{
	//set OpenGL context attributions,now can only set six attributions:
	//设置OpenGL上下文属性,现在只能设置6个属性:
	//red,green,blue,alpha,depth,stencil
	//红,绿,蓝,透明度,深度、模板

	//一个结构体
    GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};
	//静态函数
    GLView::setGLContextAttrs(glContextAttrs);
}

// If you want to use packages manager to install more packages, 
//如果您想使用包管理器安装更多的包,
// don't modify or remove this function
//请勿修改或删除此函数
//作用:注册所有包
static int register_all_packages()
{
    return 0; //flag for packages manager
}

bool AppDelegate::applicationDidFinishLaunching() {
    // initialize director
	//这里返回的是Director的单例
    auto director = Director::getInstance();

	//获取Director实例中的OpenGL视图对象
	//GLView代表OpenGL视图类,用于显示游戏图像
	//这样就可以通过glview来操作OpenGL视图,进行渲染显示等操作。
    auto glview = director->getOpenGLView();
	
	//判断glview对象是否为空,为空则创建GLView对象
    if(!glview) {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
        glview = GLViewImpl::createWithRect("project", Rect(0, 0, designResolutionSize.width, designResolutionSize.height));
#else
        glview = GLViewImpl::create("project");
#endif
        director->setOpenGLView(glview);
    }

    // turn on display FPS
	//显示帧率  默认是显示
    director->setDisplayStats(true);

    // set FPS. the default value is 1.0/60 if you don't call this
	//设置帧率 如果不调用,默认值是1.0/60,即1秒60帧
    director->setAnimationInterval(1.0 / 60);

    // Set the design resolution
	//设置设计分辨率
    glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, ResolutionPolicy::NO_BORDER);

	/*从80行,可以删除*******************/
	//用Size对象获取当前尺寸
    Size frameSize = glview->getFrameSize();

    // if the frame's height is larger than the height of medium size.
	//如果框架的高度大于中等尺寸的高度。
    if (frameSize.height > mediumResolutionSize.height)
    {        
        director->setContentScaleFactor(MIN(largeResolutionSize.height/designResolutionSize.height, largeResolutionSize.width/designResolutionSize.width));
    }
    // if the frame's height is larger than the height of small size.
	// 如果框架的高度大于尺寸的高度。
    else if (frameSize.height > smallResolutionSize.height)
    {        
        director->setContentScaleFactor(MIN(mediumResolutionSize.height/designResolutionSize.height, mediumResolutionSize.width/designResolutionSize.width));
    }
    // if the frame's height is smaller than the height of medium size.
	//如果框架的高度小于中等尺寸的高度。
    else
    {        
        director->setContentScaleFactor(MIN(smallResolutionSize.height/designResolutionSize.height, smallResolutionSize.width/designResolutionSize.width));
    }
	/*****************到102行,可以删除当不行的时候*/

	//注册Cocos2d-x引擎中内置的所有组件包。
    register_all_packages();

    // create a scene. it's an autorelease object
	//创建场景并获取
    auto scene = HelloWorld::createScene();

    // run
	//使用导演运行场景 只有导演能运行场景
    director->runWithScene(scene);

    return true;
}

// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
//此函数将在应用处于非活动状态时调用。当有电话时,它也会被调用
void AppDelegate::applicationDidEnterBackground() {

	//导演类得到实例         停止动画
    Director::getInstance()->stopAnimation();

    // if you use SimpleAudioEngine, it must be pause
	//如果使用SimpleAudioEngine,在切换到后台时需要暂停背景音乐。
	//暂停Cocos2d-x中的背景音乐的
    // SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}

// this function will be called when the app is active again
//这个函数将在应用再次激活时被调用
void AppDelegate::applicationWillEnterForeground() {
    Director::getInstance()->startAnimation();

    // if you use SimpleAudioEngine, it must resume here
	//如果使用了SimpleAudioEngine这个音频引擎, 必须在这里恢复背景音乐的播放。
	//恢复Cocos2d-x中暂停的背景音乐的播放。
    // SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}

HelloWorldScene.h

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"

/*自己添加这两行*/
using namespace cocos2d;
将代码文件字符集设置为UTF-8编码
#pragma execution_character_set("utf-8")

//HelloWorld场景
class HelloWorld : public cocos2d::Layer
{
public:
	//因此要做三件事
	/*
	1.创建自己
	2.创建以后要初始化自己
	3.创建初始化自己后,要能把自己放到一个场景里,提供给外界使用
	*/

	//*2*对外提供的场景创建接口
    static cocos2d::Scene* createScene();

	//*3*初始化函数 可以添加override表示覆盖
    virtual bool init()override;	
    
    // a selector callback
	//回调函数 参数的意思是
    void menuCloseCallback(cocos2d::Ref* pSender);
    
	
    // implement the "static create()" method manually
	//*1*创建此类对象
	//此处有两种方式
		//第一种如下(已注释)
    //CREATE_FUNC(HelloWorld);
		//第二种如下: 
	//创建自己当然返回自己
	//所有的create()都是返回自己对象的指针 自己写就需要实现 转到CREATE_FUNC的定义,然后修改再重写
	static HelloWorld* create();
};

#endif // __HELLOWORLD_SCENE_H__

HelloWorldScene.cpp

#include "HelloWorldScene.h"

USING_NS_CC;

//自己写的创建自己的函数 和宏定义的CREATE_FUNC()一样
HelloWorld* HelloWorld::create()
{
	//创建对象,申请内存 让new申请内存失败时,不抛出异常
	HelloWorld* pRet = new(std::nothrow) HelloWorld();
	//pRet不为空,即内存申请成功
	//且此时会调用本对象的初始化函数init(),若失败直接就跳出了,所以很巧妙
	if (pRet&&pRet->init())
	{
		//将该对象加入自动释放池中,引擎会帮我们在无用时释放内存
		pRet->autorelease();
		//返回场景
		return pRet;
	}
	//申请内存失败或者初始化失败
	else
	{
		//释放内存 空指针也是能够释放的
		delete pRet;
		//指针置空
		pRet = nullptr;
		//返回空
		return nullptr;
	}
}


//为外界提供一个创建好的场景
Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
	//该场景对象是会自动释放的
    auto scene = Scene::create();
    
    // 'layer' is an autorelease object
	//创建HelloWorld层,该对象是会自己释放的
    auto layer = HelloWorld::create();

    // add layer as a child to scene
	//将该层添加到场景上
    scene->addChild(layer);

    // return the scene
	//放回该场景
    return scene;
}

// on "init" you need to initialize your instance
//在init()中初始化自己的对象
bool HelloWorld::init()
{
    //
    // 1. super init first
	//首先初始化父类,若父类初始化失败,则子类也不需要初始化了
    if ( !Layer::init() )
    {
		//初始化失败
        return false;
    }
    
/*65-128可删除,自己写*/
	
	//用导演单例获得可视区域大小,导演类是单例模式
	Size visibleSize = Director::getInstance()->getVisibleSize();
	//用导演单例获得可见区域的原点坐标
	Vec2 origin = Director::getInstance()->getVisibleOrigin();

	/
	// 2. add a menu item with "X" image, which is clicked to quit the program
	//添加一个带有“X”图像的菜单项,点击该菜单项可退出程序
	//    you may modify it.
	//你可以修改它

	// 添加一个“关闭”图标以退出进度。它是一个自动释放对象,create()获得的对象都是自动释放的
	//菜单项
	auto closeItem = MenuItemImage::create(
		"CloseNormal.png",
		"CloseSelected.png",
		CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));

	closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width / 2,
		origin.y + closeItem->getContentSize().height / 2));

	// create menu, it's an autorelease object
	//创建一个菜单,将菜单项添加进来
	auto menu = Menu::create(closeItem, NULL);
	//设置菜单坐标
	menu->setPosition(Vec2::ZERO);
	//将菜单添加到层上(菜单作为层的子节点),图层为1
	this->addChild(menu, 1);

	/
	// 3. add your codes below...
	//在下面添加你的代码…
		

	// add a label shows "Hello World"
	//添加一个标签显示“Hello World”
	// create and initialize a label
	//创建并初始化标签

	auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24);

	// position the label on the center of the screen
	//设置坐标
	label->setPosition(Vec2(origin.x + visibleSize.width / 2,
		origin.y + visibleSize.height - label->getContentSize().height));

	// add the label as a child to this layer
	//将标签作为子节点添加到层上
	this->addChild(label, 1);

	// add "HelloWorld" splash screen"
	//创建精灵
	auto sprite = Sprite::create("HelloWorld.png");

	// position the sprite on the center of the screen
	//设置位置
	sprite->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));

	// add the sprite as a child to this layer
	//将其作为子节点添加到该层上
	this->addChild(sprite, 0);
/*65-128可删除,自己写*/

	//初始化成功
    return true;
}

//菜单项的回调函数 参数是表示这个对象
void HelloWorld::menuCloseCallback(Ref* pSender)
{
	//导演单例调用结束函数
    Director::getInstance()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值