Lua if / elseif导致不同的场景无法正常工作

时间:2015-09-14 19:57:24

标签: if-statement lua corona

此代码用于在scene1和scene2之间的计时器上从一个场景切换到另一个场景。当currentBar变量计数器达到4时,它应该转到scene3但不是。此示例以scene2开头。

local composer = require ( "composer")
local scene = composer.newScene()

    local function showScene2()
        local options = {
            effect = "slideLeft",
            time = 30,
        }
    composer.gotoScene( "scene2", options)

    end

-- create scene

function scene:createScene ( event )
local sceneGroup = self.view

end 

function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
    if ( phase == "will") then
        local background = display.newImage( "images/staveBlankgrey2.png", 240, 160)
        note1 =  display.newImage( "images/crDown.png", 130, 171)
        note2 =  display.newImage( "images/crUp.png", 320, 144)

        sceneGroup:insert( background )
        sceneGroup:insert( note1 )
        sceneGroup:insert( note2 )

    elseif ( phase == "did") then
        currentBar = currentBar + 1

这部分工作正常:

            if currentBar < 4 then 
                local function showScene2()
                    local options = {
                        effect = "slideLeft",
                        time = 30,
                    }
                composer.gotoScene( "evenBars", options)
            end
                timer.performWithDelay(tempo, showEvenBars)

本节不起作用:

            elseif currentBar == 4 then     
                local function showEndBar()
                    local options = {
                        effect = "slideLeft",
                        time = 30,
                    }
                composer.gotoScene( "endBar", options)
            end
                timer.performWithDelay(tempo, showEndBar)

            end
    end
end

function scene:hide( event )
    local sceneGroup = self.view
    local phase = event.phase
end

function scene:destroy( event )
    local sceneGroup = self.view
end

scene:addEventListener( "create", scene)
scene:addEventListener( "show", scene)
scene:addEventListener( "hide", scene)
scene:addEventListener( "destroy", scene)

return scene

我错过了什么?感谢。

1 个答案:

答案 0 :(得分:0)

我不知道创建tempocurrentBar的位置,因此我假设它们是全局变量。

关于你的问题,我可能会稍微改写它并创建一个新文件(因为scene1和scene2都将调用这个函数,将来可能会有更多的场景,所以最好将它单独分开文件)。

然后在场景中我会添加一个enterFrame事件监听器。

一些代码:

scene_swapper.lua

local M = {}

function M.returnSceneName( val)
    if val == nil then return nil
    elseif val == 4 then return "scene1"
    elseif val < 4 then return "scene2"
    end
end

return M

我场景中的事件监听器:

local sw = require("scene_swapper")
Runtime:addEventListener( "enterFrame", 
    function()
        local swap_to_scene = sw.returnSceneName( currentBar )
        if swap_to_scene ~= nil and swap_to_scene ~= composer.getSceneName( "current" ) then 
            composer.gotoScene( swap_to_scene ) 
        end
    end 
)

每帧(每秒30或60次)将检查一次enterFrame侦听器,因此当您更新currentBar值时,它将实际采取适当的操作。

如果你改变场景,也不要忘记删除enterFrame监听器。