如何在 Corona SDK 中检测按钮按下事件

在我的corona应用中,我有一个widget button来移动一个图片。我能找到onPress方法,但没找到一个方法来检查按钮是否仍然被按住。这样用户就不必一遍又一遍地点击同一个按钮来移动图片...

代码:

function move( event )
  local phase = event.phase
  if "began" == phase then
    define_robo()
    image.x=image.x+2;
  end
end

local movebtn = widget.newButton
{
  width = 50,
  height = 50,
  defaultFile = "left.png",
  overFile = "left.png",
  onPress = move,
}

任何帮助都将不胜感激...

点赞
用户2895078
用户2895078

如果你想知道用户何时移动手指或者何时松开按钮,可以为这些事件添加处理程序:

  • "moved" 指手指在屏幕上移动。
  • "ended" 指手指从屏幕上抬起。

"began" 只处理当他开始触摸屏幕的时候。

那么你的移动函数会像这样:

function move( event )
    local phase = event.phase
    if "began" == phase then
        define_robo()
        image.x=image.x+2;
    elseif "moved" == phase then
         -- your moved code
    elseif "ended" == phase then
         -- your ended code
    end
end

-- 根据评论进行更新: 使用以下代码,将 nDelay 替换为每次移动之间的延迟,将 nTimes 替换为你想要执行移动的次数:

function move( event )
    local phase = event.phase
    if "began" == phase then
        local nDelay = 1000
        local nTimes = 3

        define_robo()
        timer.performWithDelay(nDelay, function() image.x=image.x+2 end, nTimes )
    end
end
2013-10-23 14:18:45
用户1979583
用户1979583

尝试这个:

local image = display.newRect(100,100,50,50)  -- 你的图片
local timer_1  -- 定时器

local function move()
  print("移动...")
  image.x=image.x+2;
  timer_1 = timer.performWithDelay(10,move,1) -- 你可以根据需要设置时间
end

local function stopMove()
  print("停止移动...")
  if(timer_1)then timer.cancel(timer_1) end
end

local movebtn = widget.newButton {
  width = 50,
  height = 50,
  defaultFile = "obj1.png",
  overFile = "obj1.png",
  onPress = move,       -- 当你“按下”按钮时会调用此函数
  onRelease = stopMove, -- 当你“释放”按钮时会调用此函数
}

继续编写代码... :)

2013-10-24 04:24:33