checkbox.lua 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. local g = love.graphics
  2. require 'lib/component'
  3. Checkbox = extend(Component)
  4. function Checkbox:activate()
  5. self.value = self.value == nil and false or self.value
  6. self.scale = 1
  7. self.prevScale = self.scale
  8. self.factor = 0
  9. self.prevFactor = self.factor
  10. self.hoverDirty = false
  11. end
  12. function Checkbox:update()
  13. self.prevScale = self.scale
  14. self.prevFactor = self.factor
  15. local mx, my = love.mouse.getPosition()
  16. local ox, oy = self:getOffset()
  17. mx, my = mx + ox, my + oy
  18. local hover = self:contains(mx, my)
  19. self.scale = math.lerp(self.scale, hover and 1.15 or 1, math.min(16 * ls.tickrate, 1))
  20. self.factor = math.lerp(self.factor, self.value and 1 or 0, math.min(16 * ls.tickrate, 1))
  21. if self:contains(mx, my) then
  22. if not self.hoverDirty and not self.gooey.focused then
  23. ctx.sound:play('juju1', function(sound) sound:setPitch(.75) end)
  24. self.hoverDirty = true
  25. end
  26. else
  27. self.hoverDirty = false
  28. end
  29. end
  30. function Checkbox:render()
  31. local u, v = ctx.u, ctx.v
  32. local x, y, r = unpack(self.geometry())
  33. local factor = math.lerp(self.prevFactor, self.factor, ls.accum / ls.tickrate)
  34. local scale = math.lerp(self.prevScale, self.scale, ls.accum / ls.tickrate)
  35. local radius = scale * r
  36. if self.value then g.setColor(0, 0, 0, 200)
  37. else g.setColor(0, 0, 0, 100) end
  38. g.circle('fill', x, y, radius, 20)
  39. g.setColor(255, 255, 255, 80 + (self.value and 170 or 0))
  40. if self.value then g.setColor(100, 200, 50) end
  41. g.setLineWidth(2)
  42. g.circle('line', x, y, radius, 20)
  43. g.setLineWidth(1)
  44. g.setFont('mesmerize', r * 1.4)
  45. g.setColor(255, 255, 255, 180 + (75 * factor))
  46. g.print(self.label, x + r + 1.4 * r, y - g.getFont():getHeight() / 2)
  47. end
  48. function Checkbox:mousepressed(mx, my, b)
  49. end
  50. function Checkbox:mousereleased(mx, my, b)
  51. local ox, oy = self:getOffset()
  52. mx, my = mx + ox, my + oy
  53. if b == 'l' and self:contains(mx, my) and not self.gooey.focused then
  54. ctx.sound:play('juju1', function(sound) sound:setPitch(1) end)
  55. self:toggle()
  56. end
  57. end
  58. function Checkbox:toggle()
  59. self.value = not self.value
  60. self.scale = self.value and 1.4 or .9
  61. self:emit('change', {component = self})
  62. end
  63. function Checkbox:contains(mx, my)
  64. local x, y, r = unpack(self.geometry())
  65. local font = g.setFont('mesmerize', r * 1.4)
  66. local x1 = x - r
  67. local y1 = y - r
  68. local str = self.label
  69. return math.inside(mx, my, x1, y1, r + r + 1.4 * r + font:getWidth(str), font:getHeight())
  70. end