Corona库

我想添加按钮,只有在停止按下它们之前,它们才会持续执行其功能。

例如,在马里奥游戏中,一旦我们开始按向前的按钮,马里奥将继续移动,直到我们离开该按钮,我们不必一遍又一遍地按下前进按钮来移动。

原文链接 https://stackoverflow.com/questions/6174907

点赞
stackoverflow用户686008
stackoverflow用户686008

我假设你的问题是“如何创建一个按钮,它可以在按下并持续到松开时一直保持动作?” 首先添加一个“触摸”事件监听器。

触摸事件有几个阶段,分别是触摸的开始和结束。因此,在监听器函数中使用 if/else 来响应不同的阶段。

if event.phase=="began" then
  Runtime.addEventListener("enterFrame", doSomething)
elseif event.phase=="ended" then
  Runtime.removeEventListener("enterFrame", doSomething)

现在在 doSomething 函数中移动马里奥。

2011-05-31 11:32:18
stackoverflow用户1542404
stackoverflow用户1542404

上面的代码会在所有时间都运行,因为它有一个enterFrame的监听器,你应该需要更像这样的代码...

    local function moveLeft(event)
    if event.phase=="began" then
    character.x=character.x+1
    elseif event.phase="ended" then
    --什么也不做,无论如何它都不会再移动了
    end
    end

local leftbutton=display.newImage("bla bla bla.png")

leftButton:addEventListener("touch",moveLeft)

当你使用touch事件时,直到你松开而且这个事件也跟tap不一样,tap必须要在相当快的速率松开,并且事件只在你松开时被注册。

2012-07-21 08:40:12