Lua中使用if/elseif来导向不同的场景不起作用。

这段代码旨在定时器在场景1和场景2之间交换。当currentBar变量计数器达到4时,应该转到场景3,但没有。此示例以场景2开始。

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

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

-- 创建场景
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

我错过了什么?谢谢。

点赞
用户2524586
用户2524586

我没有看到 tempocurrentBar 是在哪里创建的,所以我会假设它们是全局变量。

关于你的问题,我可能会重新编写一下,并创建一个新的文件(因为场景1和场景2都会调用此函数,而且将来可能会有更多的场景,所以最好将它放在单独的文件中)。

然后,在场景中我会添加一个 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
)

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

另外,不要忘记在更改场景时删除 enterFrame 监听器。

2015-09-19 20:52:04