Quick-Cocos2d-x 捋一捋框架流程

一直比較關注Quick Lua,但是項目中一直使用的公司自有的Lua框架,所以一直沒機會在實際中使用下Quick Lua。看到羣裏很多人都在用這個,我在這裏梳理下開始使用的流程吧,我主要是說下實際使用上的流程問題。


比如很多學習者甚至不知道enterScene("MainScene") 爲什麼裏面可以是個字符串?當然如果你已經很熟悉框架了,這篇文章就可以跳過了,呵呵。

下面開始吧!

一、前置準備

1、安裝下載之類的,官方論壇寫的很清楚了,我就不說了。http://wiki.quick-x.com/doku.php?id=zh_cn:get_started_create_new_project
2、關於IDE,我使用的IEDA,配置導出的api代碼提示,還是挺方便的。http://wiki.quick-x.com/doku.php?id=zh_cn:get_started_install_intellij_idea

二、新建一個工程

新建之後,你首先看到的main.lua啓動到MyApp.lua。

1
require("app.MyApp").new():run()
看MyApp.lua文件:
1、require("app.MyApp")
這裏執行的MyApp.lua的代碼是:

1
2
local MyApp = class("MyApp", cc.mvc.AppBase)  -- 繼承cc.mvc.AppBase
returnMyApp
////////////////////
MyApp類是從AppBase類繼承過來的,AppBase類是是Quick裏的MVC架構中裏的重要的一環
framework/cc/mvc/AppBase.lua     ModelBase.lua
////////////////////
這時候,你得到了MyApp這個類(lua關於類的實現網上很多)。

2、require("app.MyApp").new()

MyApp.new()執行後,執行的代碼是:

1
2
3
function MyApp:ctor()
    MyApp.super.ctor(self)
end
爲什麼new()了之後會執行MyApp:ctor()?請看function.lua下的function class(classname, super)方法:
1
2
3
4
5
6
7
8
function cls.new(...)
            local instance = cls.__create(...)
            -- copy fields from classto native object
            fork,v in pairs(cls) doinstance[k] = v end
            instance.class= cls
            instance:ctor(...)
            returninstance
end
可以看到,在class的實現方法裏面,給每個創建的類聲明瞭一個new()方法,方法裏面調用了ctor()構造方法(ctor只是個名字,所以不是有些人認爲的new了之後,當然會調用構造方法,lua沒有類,只是我們模仿了類)

3、require("app.MyApp").new():run()

這時候調用了

1
2
3
4
function MyApp:run()
    CCFileUtils:sharedFileUtils():addSearchPath("res/")
    self:enterScene("MainScene")
end
所以進到了MainScene.lua。

對於MyApp.lua文件,如果我修改成下面的樣子,是不是你就理解了上面所做的事情:
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
-- 聲明類
MyApp = class("MyApp", cc.mvc.AppBase)
 
 
--- 類構造方法
--
function MyApp:ctor()
    MyApp.super.ctor(self)
end
 
--- 對應cpp版的staticcreate()方法
--
function MyApp:create()
    local myApp = MyApp.new()
    myApp:init()
end
 
--- 你自己的方法
-- @param self
--
local function launchMainScene(self)
    CCFileUtils:sharedFileUtils():addSearchPath("res/")
    self:enterScene("MainScene")
end
 
--- init 方法
--
function MyApp:init()
    -- add code here
    launchMainScene(self)
end
1
 
對應的main.lua將原來的require("app.MyApp").new():run()

修改爲:

1
2
require("app.MyApp")
MyApp:create()
這樣你是不是更容易理解了,哈哈。

三、MainScene.lua
enterScene("MainScene") 爲什麼可以切換場景?
我們看下MyApp的父類AppBase裏面:

1
2
3
4
5
6
function AppBase:enterScene(sceneName, args, transitionType, time, more)
    local scenePackageName = self. packageRoot .. ".scenes.".. sceneName
    local sceneClass = require(scenePackageName)
    local scene = sceneClass.new(unpack(totable(args)))
    display.replaceScene(scene, transitionType, time, more)
end
1
 
這樣你能理解了爲什麼連require文件都沒有就能調用MainScene,當然你要留意下,它require時候的文件路徑,scene默認寫的app/scenes文件夾

好了,其他的應該按照上面的思路基本都能知道爲什麼了。我就不一一列舉了。


來源網址:http://www.cocos2dev.com/?p=535

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