MVC简介
MVC,即Model View Controller。Model(模型),一般负责数据的处理;View(视图),一般负责界面的显示;Controller(控制器),一般负责前端的逻辑处理。拿一款手机游戏来说,界面UI的显示、布局等就是View负责;点击了按钮,手势的滑动等操作由Controller来处理;游戏中需要的数据资源就交给Model。
其中cocos、Controller、Model、View这个不用多说,Event里面保存的全局消息类型,Managers是用于管理游戏中的东东的,比如管理资源,管理各种场景切换,层的切换等等。Utilities提供一些工具类,比如字符串的处理等。大家也可以根据自己的需求来定制目录,比如定义一个NetCenter文件夹,专门用于处理网络的。本例子中没有用到数据操作和工具类,所以这两个文件夹为空。
流程实例
我们以游戏的运行流程为线索来展开说明。运行项目,进入到main.lua文件,来看看main函数:
local function main()
collectgarbage(collect)
-- avoid memory leak
collectgarbage(setpause, 100)
collectgarbage(setstepmul, 5000)
-- initialize director
local director = cc.Director:getInstance()
--turn on display FPS
director:setDisplayStats(true)
--set FPS. the default value is 1.0/60 if you don't call this
director:setAnimationInterval(1.0 / 60)
cc.Director:getInstance():getOpenGLView():setDesignResolutionSize(320, 480, 1)
--create scene
local scene = require(GameScene)
local gameScene = scene:startGame()
end
我们最后调用了GameScene类中的startGame函数,来看看GameScene这个类:
require(Managers.SceneManager)
require(Managers.LayerManager)
local GameScene = class(GameScene)
local scene = nil
function GameScene:startGame()
--初始化
scene = cc.Scene:create()
if cc.Director:getInstance():getRunningScene() then
cc.Director:getInstance():replaceScene(scene)
else
cc.Director:getInstance():runWithScene(scene)
end
SceneManager:initLayer(scene)
self:enterGame()
end
function GameScene:enterGame()
LayerManager:getInstance():gotoLayerByType(LAYER_TYPE_MAIN)
end
return GameScene
在startGame函数中,我们创建了一个空场景,然后调用SceneManager场景管理器来初始化场景。最后调用enterGame函数正式进入游戏主界面,其中enterGame函数中又有一个LayerManager层管理器。我们来看看这两个管