在2020年學習cocos遊戲引擎

常用鏈接

Cocos2d-x 用戶手冊

環境搭建

macOS 10.15.6
Xcode 11.5
cocos2d-x 3.17.2
cmake 3.17.3

創建工程

採用cocos2d-x 3.17版本可直接通過cocos console創建,4.0版本需要額外通過cmake生成.xcodeproj文件。

cocos new 工程名 -p com.cocos2dx.工程名 -l cpp -d 目錄名(/Users/xxx)

架構分析

cocos目錄結構
Classes存放邏輯代碼,Resource存放資源文件
C++文件由.hpp(聲明)和.cpp(定義及初始化)組成

AppDelegate.h

#ifndef  _APP_DELEGATE_H_  // 宏定義 保證頭文件不需要多次編譯
#define  _APP_DELEGATE_H_

#include "cocos2d.h"

class  AppDelegate : private cocos2d::Application
{
public:
    AppDelegate(); // 構造
    virtual ~AppDelegate();  // 虛析構
    virtual void initGLContextAttrs();  // 初始化openGL參數
    virtual bool applicationDidFinishLaunching();   // 應用進入
    virtual void applicationDidEnterBackground();   // 應用中途退入後臺
    virtual void applicationWillEnterForeground();  // 應用中途來電
    // 虛析構函數能夠保證當用一個基類的指針刪除一個派生類的對象時,派生類的析構函數會被調用
	// 虛函數被繼承後仍然是虛擬函數,可以省略掉關鍵字“virtual”
};

#endif // _APP_DELEGATE_H_

AppDelegate.cpp

#include "AppDelegate.h"
#include "MainScene.h"

USING_NS_CC;
// visiableSize 
static cocos2d::Size designResolutionSize = cocos2d::Size(1386, 640);
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() 
{
}

void AppDelegate::initGLContextAttrs()
{
    // set OpenGL context attributes: red, green, blue, alpha, depth, stencil, multisamplesCount
    GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8, 0};

    GLView::setGLContextAttrs(glContextAttrs);
}

bool AppDelegate::applicationDidFinishLaunching() {
    auto director = Director::getInstance();
    auto glview = director->getOpenGLView();
    if(!glview) {
        director->setOpenGLView(glview);
    }

    // 顯示演示信息
    director->setDisplayStats(true);

    // 設置幀率
    director->setAnimationInterval(1.0f / 60);

    // designResolutionSize 設計分辨率大小
    glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, ResolutionPolicy::FIXED_WIDTH);
    // frameSize 手機分辨率大小
    auto frameSize = glview->getFrameSize();
    
    // 適配策略
	if (frameSize.height > mediumResolutionSize.height) {
		director->setContentScaleFactor(MIN(largeResolutionSize.height/designResolutionSize.height, largeResolutionSize.width/designResolutionSize.width));
	} else if (frameSize.height > smallResolutionSize.height) {
	director->setContentScaleFactor(MIN(mediumResolutionSize.height/designResolutionSize.height, mediumResolutionSize.width/designResolutionSize.width));
	} else {
	director->setContentScaleFactor(MIN(smallResolutionSize.height/designResolutionSize.height, smallResolutionSize.width/designResolutionSize.width));
	}
	
    // 創建場景
    auto mainScene = MainScene::createScene();
    // 導演類調度場景
    director->runWithScene(mainScene);
    
    return true;
}

void AppDelegate::applicationDidEnterBackground() {
    Director::getInstance()->stopAnimation();
}
void AppDelegate::applicationWillEnterForeground() {
    Director::getInstance()->startAnimation();
}

MainScene.hpp

#ifndef __MAIN_SCENE_H__
#define __MAIN_SCENE_H__

#include "cocos2d.h"
// 繼承Scene
class MainScene : public cocos2d::Scene
{
public:
    static cocos2d::Scene* createScene(); // 靜態,用於獲取場景對象

    virtual bool init() override; // 初始化場景

    CREATE_FUNC(MainScene); // 
};

#endif // __HELLOWORLD_SCENE_H__

MainScene.cpp

#include "MainScene.h"

USING_NS_CC; // 等同於 using namespace cocos2d
Scene* HelloWorld::createScene()
{
    auto scene = Scene::create(); // 創建一個Scene對象
    auto layer = MainScene::create(); // 創建一個MainScene對象
    scene->addChild(layer); // 將layer加入到場景中
    return scene;
}

bool mainScene::init()
{
    if ( !Scene::init() )
    {
        return false;
    }
    // 在這裏添加邏輯代碼
    return true;
}

通過圖集加載圖片

// 使用texture package將美術提供的tps文件轉化爲plist和pvr.czz文件
ZipUtils::setPvrEncryptionKey() // plist->czz需要md5祕鑰解碼
SpriteFrameCache *sfc = SpriteFrameCache::getInstance(); // 定義SpriteFrameCache
sfc->addSpriteFrameWithFile("xxx.plist"); // 調用實例方法addSpriteFrameWithFile()

auto mainBg = Sprite::createWithSpriteFrameName("xxx.png"); // 使用圖集加載圖片

添加Button

// include "ui/CocosGUI.h"
auto btn = cocos2d::ui::Button::create();
btn->loadTextures("xxx_normal.png", "xxx_pressed.png", "", cocos2d::ui::Widget::TextureResType::PLIST);
btn->setPosition(Vec2(20, 100));
this->addChild(btn);

添加文本

auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24);
auto label2 = Label::createWithSystemFont("Hello World", "Arial", 24);
label->setPosition(Vec2(20, 100));
this->addChild(label);

添加事件

// 方法一:設置監聽器,由_eventDispatcher派發事件。需要注意的是,在添加到多個對象時,需要使用clone()方法。
auto listener = EventListenerTouchOneByOne::create();
	listener->setSwallowTouches(true);
	listener->onTouchBegan = [=](Touch *touch, Event* event) {
		printf("Touch事件觸發");
		return true;
 };
 _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, btn);
    
// 方法二:直接通過對象掛載事件監聽器
btn->addTouchEventListener([&](Ref* sender, cocos2d::ui::Widget::TouchEventType type){
        switch (type)
        {
                default:
                    break;
                case ui::Widget::TouchEventType::BEGAN:
                    break;
                case ui::Widget::TouchEventType::ENDED:
                    break;
        }
});
// []:默認不捕獲任何變量;
// [=]:默認以值捕獲所有變量;
// [&]:默認以引用捕獲所有變量;
// [x]:僅以值捕獲x,其它變量不捕獲;

添加動畫

// 繞y軸旋轉180,5s
auto* rotateBy = RotateBy::create(5.0f, Vec3(0, 180, 0));
// 定義回調函數
auto* callFun = CallFunc::create(CC_CALLBACK_0(MainScene::rotateFun, this));
// 定義動畫序列
auto* sequence = Sequence::create(rotateBy, callFun, NULL);
sprite->runAction(sequence);

添加定時器

// 在init()中進行調用
scheduleUpdate(); // 重寫Update(float dt)方法
schedule(schedule_selector(MainScene::myUpdate), 0.2f);  // 自定義方法

讀取XML文件

// #include <tinyxml2/tinyxml2.h>
auto doc = new tinyxml2::XMLDocument();
doc->Parse(FileUtils::getInstance()->getStringFromFile("data.xml").c_str());  // 調用解析函數
auto root = doc->RootElement(); // 從根節點開始查找
for (auto e = root->FirstChildElement(); e != NULL; e = e->NextSiblingElement()) {
    for (auto attr = e->FirstAttribute(); attr != NULL; attr = attr->Next()) {
		printf("%s %s\n", attr->Name(), attr->Value());
    }

讀取json文件

// #include <json/document.h>
rapidjson::Document d;
d.Parse<0>(FileUtils::getInstance()->getStringFromFile("data.json").c_str()); // 調用解析函數 <0>默認解析方式
printf("%s",d[0]["name"].GetString());

讀取本地存儲

UserDefault::getInstance()->getIntegerForKey("int"); // 設置key
UserDefault::getInstance()->setIntegerForKey("int", 999); // 讀取key
printf("saved file path is %s\n", UserDefault::getInstance()->getXMLFilePath().c_str()); // 存儲路徑

網絡編程

弱聯網:CURL庫
強聯網:socket


開發經驗

最小化在編寫代碼前需要了解的信息

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章