在main中
--create scene local scene = require("GameScene") local gameScene = scene.create() gameScene:playBgMusic() if cc.Director:getInstance():getRunningScene() then cc.Director:getInstance():replaceScene(gameScene) else cc.Director:getInstance():runWithScene(gameScene) end
require加载了GameScene,runWithScene用与第一次创建一个场景,它会将场景加入Director的主线程中,已经运行的场景是不能调用的。并且runWithScene会pushScene。replaceScene用用于场景间的替换,与pushScene不同的是被替换的场景不会保留到栈中。
1.GameScene
来看看GameScene中的代码
local GameScene = class("GameScene",function() return cc.Scene:create() end) function GameScene.create() local scene = GameScene.new() scene:addChild(scene:createLayer()) return scene end
function GameScene:ctor() self.visibleSize = cc.Director:getInstance():getVisibleSize() self.origin = cc.Director:getInstance():getVisibleOrigin() end function GameScene:playBgMusic() end -- create layer function GameScene:createLayer() local rootNode = cc.CSLoader:createNode("MainScene.csb") local menuPopup,menuTools,effectID local function menuCallbackClose() cc.Director:getInstance():endToLua() end -- add handler for close item local menuToolsItem = rootNode:getChildByName("Button_1") menuToolsItem:addTouchEventListener(menuCallbackClose) return rootNode end return GameScene
local GameScene = class("GameScene",function()return cc.Scene:create()end) Lua是一门脚本语言,不是面向对象的,所以是通过table来实现类的模拟。class函数的的参数是类名及要继承的父类。 local rootNode = cc.CSLoader:createNode("MainScene.csb")从MainScene文件中创建节点,MainSence.csb是CocoStudio导出的资源描述文件。
原文链接:https://www.f2er.com/cocos2dx/345426.html