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
return MyApp
这时候,你得到了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 class to native object
for k,v in pairs(cls) do instance[k] = v end
instance. class = cls
instance:ctor(...)
return instance
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版的 static create()方法
--
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,more)
end
1
这样你能理解了为什么连require文件都没有就能调用MainScene,当然你要留意下,它require时候的文件路径,scene认写的app/scenes文件

好了,其他的应该按照上面的思路基本都能知道为什么了。我就不一一列举了。

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...