【学习笔记】Cocos2d-x Lua脚本引擎之HelloLua分析笔记

来源:互联网 发布:晁然的淘宝店名叫什么 编辑:程序博客网 时间:2024/05/06 00:37
-- for CCLuaEngine tracebackfunction __G__TRACKBACK__(msg)    print("----------------------------------------")    print("LUA ERROR: " .. tostring(msg) .. "\n")    print(debug.traceback())    print("----------------------------------------")endlocal function main()    -----------------------------------------------------------------    -- avoid memory leak    collectgarbage("setpause", 100)    collectgarbage("setstepmul", 5000)    --[[-------------------------------------------------------------    补充说明:        collectgrabage(opt [, arg])        功能:垃圾收集器的通用接口,用于操作垃圾收集器        参数:            opt--操作方法标志            "stop" : 停止垃圾收集器            "restart" : 重启垃圾收集器            "collect" : 执行一次全垃圾收集循环            "count" : 返回当前Lua中使用的内存量(以KB为单位)            "step" : 单步执行一个垃圾收集.步长"size"由参数arg指定.如果完成一次收集循环,将返回True            "setpause" : 设置arg/100的值作为暂定收集的时长            "setstepmul" : 设置arg/100的值,作为步长的增幅(即新步长 = 旧步长*(arg/100))    --]]-------------------------------------------------------------                    -----------------------------------------------------------------    --自定义打印函数,将字符串打印出来    --其实这里可以调用CCLuaLog函数来打印字符串    local cclog = function(...)        print(string.format(...))    end    -----------------------------------------------------------------                    -----------------------------------------------------------------    --包含hello2这个脚本,该脚本定义了myadd(x, y)函数    require "hello2"    cclog("result is " .. myadd(3, 5))    -----------------------------------------------------------------                    -----------------------------------------------------------------    --获取可视区域    local visibleSize = CCDirector:sharedDirector():getVisibleSize()    --获取可是区域的原点坐标,OpenGL坐标系 左下角为原点    local origin = CCDirector:sharedDirector():getVisibleOrigin()    -----------------------------------------------------------------    -- add the moving dog    local function creatDog()        --dog.png的规格是 210*95, 由两个frame组成规格皆为105*95        local frameWidth = 105        local frameHeight = 95        -- create dog animate        local textureDog = CCTextureCache:sharedTextureCache():addImage("dog.png")        --rect用于捕捉textureDog的纹理并赋给frame0        local rect = CCRectMake(0, 0, frameWidth, frameHeight)        local frame0 = CCSpriteFrame:createWithTexture(textureDog, rect)        --rect用于捕捉textureDog的纹理并赋给frame1        rect = CCRectMake(frameWidth, 0, frameWidth, frameHeight)        local frame1 = CCSpriteFrame:createWithTexture(textureDog, rect)                --创建松鼠精灵        local spriteDog = CCSprite:createWithSpriteFrame(frame0)        spriteDog.isPaused = false        spriteDog:setPosition(origin.x, origin.y + visibleSize.height / 4 * 3)                                --接下来的代码是要创建一个CCAction对象,让spriteDog来run这个CCAction对象        --步骤如下:          --1.使用数组animFrames保存序列帧          --2.利用该数组创建一个CCAnimation对象          --3.利用CCAnimation对象创建CCAnimate对象          --4.利用CCAnimate对象创建CCAction对象          --5.run这个CCAction                local animFrames = CCArray:create()        animFrames:addObject(frame0)        animFrames:addObject(frame1)        local animation = CCAnimation:createWithSpriteFrames(animFrames, 0.5)        local animate = CCAnimate:create(animation);        spriteDog:runAction(CCRepeatForever:create(animate))        -----------------------------------------------------------------        -- moving dog at every frame        local function tick()            --如果暂停了,那么返回,不对spriteDog做任何操作            if spriteDog.isPaused then return end                        --根据spriteDog的当前position来判断下一个position            local x, y = spriteDog:getPosition()            if x > origin.x + visibleSize.width then                x = origin.x            else                x = x + 1            end                        --更新位置            spriteDog:setPositionX(x)        end        --设置每帧调用trick函数        CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(tick, 0, false)        return spriteDog    end    -- create farm    local function createLayerFarm()        local layerFarm = CCLayer:create()        -- add in farm background        local bg = CCSprite:create("farm.jpg")        bg:setPosition(origin.x + visibleSize.width / 2 + 80, origin.y + visibleSize.height / 2)        layerFarm:addChild(bg)        -- add land sprite        for i = 0, 3 do            for j = 0, 1 do                local spriteLand = CCSprite:create("land.png")                spriteLand:setPosition(200 + j * 180 - i % 2 * 90, 10 + i * 95 / 2)                layerFarm:addChild(spriteLand)            end        end        -- add crop        local frameCrop = CCSpriteFrame:create("crop.png", CCRectMake(0, 0, 105, 95))        for i = 0, 3 do            for j = 0, 1 do                local spriteCrop = CCSprite:createWithSpriteFrame(frameCrop);                spriteCrop:setPosition(10 + 200 + j * 180 - i % 2 * 90, 30 + 10 + i * 95 / 2)                layerFarm:addChild(spriteCrop)            end        end        -- add moving dog        local spriteDog = creatDog()        layerFarm:addChild(spriteDog)                        -- handing touch events        local touchBeginPoint = nil                --触摸开始        local function onTouchBegan(x, y)            cclog("onTouchBegan: %0.2f, %0.2f", x, y)            touchBeginPoint = {x = x, y = y}            spriteDog.isPaused = true            -- CCTOUCHBEGAN event must return true            return true        end                --触摸移动        local function onTouchMoved(x, y)            cclog("onTouchMoved: %0.2f, %0.2f", x, y)            if touchBeginPoint then                local cx, cy = layerFarm:getPosition()                layerFarm:setPosition(cx + x - touchBeginPoint.x,                                      cy + y - touchBeginPoint.y)                touchBeginPoint = {x = x, y = y}            end        end                --触摸结束        local function onTouchEnded(x, y)            cclog("onTouchEnded: %0.2f, %0.2f", x, y)            touchBeginPoint = nil            spriteDog.isPaused = false        end                --触屏事件获得eventType:began/moved/ended        local function onTouch(eventType, x, y)            if eventType == "began" then                   return onTouchBegan(x, y)            elseif eventType == "moved" then                return onTouchMoved(x, y)            else                return onTouchEnded(x, y)            end        end        --注册Targeted触屏事件        layerFarm:registerScriptTouchHandler(onTouch)                layerFarm:setTouchEnabled(true)        return layerFarm    end    -- create menu    local function createLayerMenu()        local layerMenu = CCLayer:create()        local menuPopup, menuTools, effectID        local function menuCallbackClosePopup()            -- stop test sound effect            SimpleAudioEngine:sharedEngine():stopEffect(effectID)            menuPopup:setVisible(false)        end        local function menuCallbackOpenPopup()            -- loop test sound effect            local effectPath = CCFileUtils:sharedFileUtils():fullPathForFilename("effect1.wav")            effectID = SimpleAudioEngine:sharedEngine():playEffect(effectPath)            menuPopup:setVisible(true)        end                -- add a popup menu        local menuPopupItem = CCMenuItemImage:create("menu2.png", "menu2.png")        menuPopupItem:setPosition(0, 0)        menuPopupItem:registerScriptTapHandler(menuCallbackClosePopup)        menuPopup = CCMenu:createWithItem(menuPopupItem)        menuPopup:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2)        menuPopup:setVisible(false)        layerMenu:addChild(menuPopup)                -- add the left-bottom "tools" menu to invoke menuPopup        local menuToolsItem = CCMenuItemImage:create("menu1.png", "menu1.png")        menuToolsItem:setPosition(0, 0)        menuToolsItem:registerScriptTapHandler(menuCallbackOpenPopup)        menuTools = CCMenu:createWithItem(menuToolsItem)        local itemWidth = menuToolsItem:getContentSize().width        local itemHeight = menuToolsItem:getContentSize().height        menuTools:setPosition(origin.x + itemWidth/2, origin.y + itemHeight/2)        layerMenu:addChild(menuTools)        return layerMenu    end    -- play background music, preload effect    -- uncomment below for the BlackBerry version    -- local bgMusicPath = CCFileUtils:sharedFileUtils():fullPathForFilename("background.ogg")    local bgMusicPath = CCFileUtils:sharedFileUtils():fullPathForFilename("background.mp3")    SimpleAudioEngine:sharedEngine():playBackgroundMusic(bgMusicPath, true)    local effectPath = CCFileUtils:sharedFileUtils():fullPathForFilename("effect1.wav")    SimpleAudioEngine:sharedEngine():preloadEffect(effectPath)    -- run    local sceneGame = CCScene:create()    sceneGame:addChild(createLayerFarm())    sceneGame:addChild(createLayerMenu())    CCDirector:sharedDirector():runWithScene(sceneGame)endxpcall(main, __G__TRACKBACK__)

原创粉丝点击