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

时间:2017-04-09 12:28:55

标签: lua love2d

我正在使用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

我敢打赌解决方案很简单,但我被困住了。有人对此有所了解吗? 感谢。

2 个答案:

答案 0 :(得分:0)

我终于知道该怎么做了。 我只需要重置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 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
                    -- to stop increment without stopping animation
                    mouseClicked.x = 0
                    mouseClicked.y = 0
                  end
             end
        end
      else b.position = "up" end -- if the player doesn t click, button back up
    --end
  end

  return pIncrement

end

答案 1 :(得分:0)

您可能会发现使用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