通过鼠标点击 love2d lua 增加整数

我正在用 lua/love2d 制作时钟视频游戏。 我发现如何检测特定区域的鼠标点击。问题是,即使我很快地点击,数字也增加了4-5个数字。我无法找到解决方案。这是我的代码:

function love.mousepressed(x, y, button, istouch)
      if button == 1 then
        mouseClicked.on = true
        mouseClicked.x = x
        mouseClicked.y = y
      end
    end

    function love.mousereleased(x, y, button, istouch)
      if button == 1 then
        mouseClicked.on = false
        mouseClicked.x = nil
        mouseClicked.y = nil
      end
    end

    function Control.Update(ppDt, pIncrement)

      local i
      for i = 1, #listButtons do
        local b = listButtons[i]
        --if b.isEnabled == true then -- if the button is showing
          if mouseClicked.on == true then -- if the player click
            if mouseClicked.x > b.x - tileWidth/2 and
               mouseClicked.x < b.x + tileWidth/2 then
                 if mouseClicked.y > b.y - tileHeight/2 and
                    mouseClicked.y < b.y + tileHeight/2 then
                      b.position = "down" -- if the button is clicked, button down
                      if b.id == 1 then pIncrement = pIncrement + 1 end
                 end
            end
          else b.position = "up" end -- if the player doesn t click, button back up
        --end
      end

      return pIncrement
    end

我敢打赌解决方案很简单,但我被卡住了。有人知道吗? 谢谢。

点赞
用户7840396
用户7840396

我终于找到了如何实现的方法。 我只需要重置 mouseClicked 列表的 x 和 y 属性。

function Control.Update(ppDt, pIncrement)

  local i
  for i = 1, #listButtons do
    local b = listButtons[i]
    --if b.isEnabled == true then -- 如果按钮正在显示
      if mouseClicked.on == true then -- 如果玩家点击
        if mouseClicked.x > b.x - tileWidth/2 and
           mouseClicked.x < b.x + tileWidth/2 then
             if mouseClicked.y > b.y - tileHeight/2 and
                mouseClicked.y < b.y + tileHeight/2 then
                  b.position = "down" -- 如果按钮被点击,向下移动按钮
                  if b.id == 1 then
                    pIncrement = pIncrement + 1
                    -- 防止动画停止而不止增加
                    mouseClicked.x = 0
                    mouseClicked.y = 0
                  end
             end
        end
      else b.position = "up" end -- 如果玩家没有点击,按钮恢复原位
    --end
  end

  return pIncrement

end
2017-04-09 13:16:49
用户2969217
用户2969217

你可能会发现使用 love.mouse.isDown() 很有用。

下面是一个完整的示例,它会跟踪用户左键单击的次数:

local clickCount, leftIsDown, leftWasDown

function love.load()
  clickCount = 0
  leftIsDown = false
  leftWasDown = false
end

function love.update(t)
  leftIsDown = love.mouse.isDown(1)

  if leftIsDown and not leftWasDown then
    clickCount = clickCount + 1
  end

  leftWasDown = leftIsDown -- keep track for next time
end

function love.draw()
  local scr_w, scr_h = love.graphics.getDimensions()
  love.graphics.print('Left clicked ' .. clickCount .. ' times', scr_w/3, scr_h/3, 0, 1.5)
end
2017-04-10 11:01:11