我所理解cocos2d-x 3.6 lua,cocos2d-xlua

來源:互聯網
上載者:User

我所理解cocos2d-x 3.6 lua,cocos2d-xlua
簡單說幾句:

    最近的遊戲項目中使用了lua指令碼來開發,項目中用到了MVC架構. 從cocos2d-x 3.6 建立lua demo, 簡單分享一下思路和一些開發中的技巧。

先簡單說說MVC,即Model View Controller。




Model(模型):一般負責資料的處理

View(視圖):一般負責介面的顯示

Controller(控制器):一般負責前端的邏輯處理

比如 :拿一款手機遊戲來說,介面UI的顯示、布局等就是View負責;點擊了按鈕,手勢的滑動等操作由Controller來處理;遊戲中需要的資料資源就交給Model。


遊戲執行個體:


我建立項目的目錄結構:


        


    在講解代碼時,先介紹下該demo是做什麼來的,沒錯,其實它就是介紹一款《殺蟲》遊戲,如:




    玩法:初始化5個血量,隨機生機向爬入洞的螞蟻或蜘蛛,直到積累進入5個蟲子,就結束遊戲。


    那麼怎麼實現該遊戲呢?請看設計順序圖表及類圖:


順序圖表:





類圖:




具體代碼:


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

require("app.MyApp"):create():run()

看MyApp.lua檔案:
1、require("app.MyApp")
這裡執行的MyApp.lua的代碼是:

local MyApp = class("MyApp", cc.load("mvc").AppBase) -- 繼承cc.mvc.AppBasefunction MyApp:onCreate()    math.randomseed(os.time())endreturn MyApp
2、require("app.MyApp").create()
MyApp.create()執行後,執行的代碼是:
function MyApp:ctor()    MyApp.super.ctor(self)end
為什麼create()了之後會執行MyApp:ctor()?請看function.lua下的function class(classname, super)方法:
cls.new = function(...)        local instance        if cls.__create then            instance = cls.__create(...)        else            instance = {}        end        setmetatableindex(instance, cls)        instance.class = cls        instance:ctor(...)        return instance    end    cls.create = function(_, ...)        return cls.new(...)    end

可以看到,在class的實現方法裡面,給每個建立的類聲明了一個new()方法,方法裡面調用了ctor()構造方法(ctor只是個名字,所以不是有些人認為的create了之後,當然會調用構造方法,lua沒有類,只是我們模仿了類)

3.require("app.MyApp").create():run()

function AppBase:run(initSceneName)    initSceneName = initSceneName or self.configs_.defaultSceneName    self:enterScene(initSceneName)end

其實:self.configs_.defaultSceneName = “MainScene”,就是進入初始介面。

對於MyApp.lua檔案,如果我修改成下面的樣子,是不是你就理解了上面所做的事情:

local AppBase = class("AppBase")-- 初始化調用function AppBase:ctor(configs)    self.configs_ = {        viewsRoot  = "app.views",        modelsRoot = "app.models",        defaultSceneName = "MainScene",    }    for k, v in pairs(configs or {}) do        self.configs_[k] = v    end    if type(self.configs_.viewsRoot) ~= "table" then        self.configs_.viewsRoot = {self.configs_.viewsRoot}    end    if type(self.configs_.modelsRoot) ~= "table" then        self.configs_.modelsRoot = {self.configs_.modelsRoot}    end    if DEBUG > 1 then        dump(self.configs_, "AppBase configs")    end    if CC_SHOW_FPS then        cc.Director:getInstance():setDisplayStats(true)    end    -- event    self:onCreate()end-- 運行情境function AppBase:run(initSceneName)    initSceneName = initSceneName or self.configs_.defaultSceneName    self:enterScene(initSceneName)end-- 選擇情境function AppBase:enterScene(sceneName, transition, time, more)    local view = self:createView(sceneName)    view:showWithScene(transition, time, more)    return viewend-- 選擇UI,即是viewfunction AppBase:createView(name)    for _, root in ipairs(self.configs_.viewsRoot) do        local packageName = string.format("%s.%s", root, name)        local status, view = xpcall(function()                return require(packageName)            end, function(msg)            if not string.find(msg, string.format("'%s' not found:", packageName)) then                print("load view error: ", msg)            end        end)        local t = type(view)        if status and (t == "table" or t == "userdata") then            return view:create(self, name)        end    end    error(string.format("AppBase:createView() - not found view \"%s\" in search paths \"%s\"",        name, table.concat(self.configs_.viewsRoot, ",")), 0)end-- 建立時調用function AppBase:onCreate()endreturn AppBase
MainScene.lua

local MainScene = class("MainScene", cc.load("mvc").ViewBase)function MainScene:onCreate()    -- add background image    display.newSprite("MainSceneBg.jpg")        :move(display.center)        :addTo(self)    -- add play button    local playButton = cc.MenuItemImage:create("PlayButton.png", "PlayButton.png")        :onClicked(function()            self:getApp():enterScene("PlayScene")   -- 進入遊戲介面        end)    cc.Menu:create(playButton)        :move(display.cx, display.cy - 200)        :addTo(self)endreturn MainScene
PlayScene.lua

local PlayScene = class("PlayScene", cc.load("mvc").ViewBase)local GameView = import(".GameView")function PlayScene:onCreate()    -- create game view and add it to stage    self.gameView_ = GameView:create()        :addEventListener(GameView.events.PLAYER_DEAD_EVENT, handler(self, self.onPlayerDead))        :start()        :addTo(self)end-- 遊戲結束調用(注意下GameView bind綁定)function PlayScene:onPlayerDead(event)    -- add game over text    local text = string.format("You killed %d bugs", self.gameView_:getKills())    cc.Label:createWithSystemFont(text, "Arial", 96)        :align(display.CENTER, display.center)        :addTo(self)    -- add exit button    local exitButton = cc.MenuItemImage:create("ExitButton.png", "ExitButton.png")        :onClicked(function()            self:getApp():enterScene("MainScene")        end)    cc.Menu:create(exitButton)        :move(display.cx, display.cy - 200)        :addTo(self)endreturn PlayScene
GameView.lua

代碼較長,就重點介紹幾段代碼:

幀頻重新整理

function GameView:step(dt)    if self.lives_ <= 0 then return end    self.addBugInterval_ = self.addBugInterval_ - dt    if self.addBugInterval_ <= 0 then        self.addBugInterval_ = math.random(GameView.ADD_BUG_INTERVAL_MIN, GameView.ADD_BUG_INTERVAL_MAX)        self:addBug()   -- 隨機產生蟲子    end    for _, bug in pairs(self.bugs_) do        bug:step(dt)    -- 蟲子爬動        if bug:getModel():getDist() <= 0 then            self:bugEnterHole(bug)  -- 進入洞穴        end    end    return selfend
載入蟲子

function GameView:addBug()    local bugType = BugBase.BUG_TYPE_ANT    -- 隨機播放螞蟻、蜘蛛    if math.random(1, 2) % 2 == 0 then        bugType = BugBase.BUG_TYPE_SPIDER    end    -- 建立螞蟻、蜘蛛模型    local bugModel    if bugType == BugBase.BUG_TYPE_ANT then        bugModel = BugAnt:create()    else        bugModel = BugSpider:create()    end    -- 載入蟲view選擇對應模型    local bug = BugSprite:create(GameView.IMAGE_FILENAMES[bugType], bugModel)        :start(GameView.HOLE_POSITION)        :addTo(self.bugsNode_, GameView.ZORDER_BUG)    self.bugs_[bug] = bug    return selfend
綁定事件

    -- bind the "event" component    cc.bind(self, "event")
通過事件,若遊戲結束後,直接跳轉PlayScene情境。像擊殺蟲、扣血等代碼就不多介紹,參考下類圖,你就明白了,我就不一一列舉了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.