【问题标题】:Stop event propagation in Corona SDK在 Corona SDK 中停止事件传播
【发布时间】:2026-01-26 21:05:02
【问题描述】:

我正在使用 Corona SDK 和 Director 1.4 创建一个应用程序。我的目标是在单击按钮 (btn_play) 时打开一个弹出窗口。

但是,我遇到了一个问题。当btn_play被点击时,它会触发openPopup(e)以及changeScene(e)(因为背景设置为执行该功能)。单击btn_play按钮时,如何阻止函数changeScene(e)执行?

这是我的游戏画面代码:

module(..., package.seeall)

local localGroup

function new()
    localGroup = display.newGroup();

    -- Background Image
    local background = display.newImageRect("background.jpg", display.contentWidth, display.contentHeight )
    background:setReferencePoint( display.TopLeftReferencePoint )
    background.x, background.y = 0, 0
    background.scene = "scene_menu";

    -- Play button
    local btn_play = display.newImageRect("grass.png", 320, 82 )
    btn_play:setReferencePoint( display.CenterReferencePoint )
    btn_play.x = display.contentWidth * 0.5
    btn_play.y = 600
    btn_play.scene = "inventory"

    localGroup:insert(background);
    localGroup:insert(btn_play);

    function changeScene(e)
        if(e.phase == "ended") then
            director:changeScene(e.target.scene);
        end
    end

    function openPopup(e)
        if(e.phase == "ended") then
            director:openPopUp(e.target.scene);
        end
    end

    background:addEventListener("touch", changeScene);
    btn_play:addEventListener("touch", openPopup);

    return localGroup;
end

【问题讨论】:

    标签: lua coronasdk corona-director


    【解决方案1】:

    只需将return 放在函数的末尾即可。它将阻止touch 到底层对象。

    function openPopup(e)
        if(e.phase == "ended") then
            director:openPopUp(e.target.scene);
            return true; -- put this in your function.
        end
    end
    

    继续编码........ :)

    【讨论】:

    • 非常好。它工作正常!完全忽略了return true的重要性
    • 很好的解决方案!多谢。只是一个问题,为什么要分号?
    • @Rayjax:分号不是强制性的。它只是用来显示行尾。
    • 所以不需要在 lua 中使用它们?你只是让我怀疑它:)