[cocos2d_lua]cocos2d_lua中的框架MVC

本文详细介绍了cocos2d_lua中MVC框架的应用,包括Model、View、Controller的角色和交互。通过流程实例展示了游戏运行过程,从main.lua开始,经由SceneManager和LayerManager管理场景和层,再到MainLayerController和MainLayerView的交互,解释了事件处理和资源管理。同时,文中也提及了cocos2dx-lua工程的启动流程以及Lua的MVC框架Sailor的基本概念。
摘要由CSDN通过智能技术生成

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层管理器。我们来看看这两个管

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值