This repository has been archived by the owner on Sep 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
button.lua
58 lines (47 loc) · 1.5 KB
/
button.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
local class = require "libs/middleclass"
Button = class("Button")
function Button:initialize(x, y, w, h, text, onPress)
-- constants
self.x = x - w / 2
self.y = y - h / 2
self.w = w
self.h = h
self.text = text
self.onPress = onPress
-- variables
self.mouseHover = false
self.alpha = 0
end
function Button:update(dt)
-- determine whether mouse is hovering over button
local mouseX = love.mouse.getX()
local mouseY = love.mouse.getY()
self.mouseHover = mouseX > self.x and mouseX < self.x + self.w and mouseY > self.y and mouseY < self.y + self.h
if self.mouseHover then
self.alpha = self.alpha + 255 * 9 * dt
else
self.alpha = self.alpha - 255 * 9 * dt
end
if self.alpha < 0 then
self.alpha = 0
elseif self.alpha > 255 then
self.alpha = 255
end
-- button pressed
if self.mouseHover and love.mouse.isDown(1) then
self.onPress()
end
end
function Button:draw()
love.graphics.setColor(213, 186, 29, self.alpha)
love.graphics.rectangle("fill", self.x - 8, self.y, self.w + 14, self.h + 1, 8)
if not self.mouseHover then
love.graphics.setColor(whiteColor.r, whiteColor.g, whiteColor.b)
love.graphics.print(self.text, self.x, self.y)
else
love.graphics.setColor(blackColor.r, blackColor.g, blackColor.b)
love.graphics.print(self.text, self.x, self.y)
end
-- reset color
love.graphics.setColor(whiteColor.r, whiteColor.g, whiteColor.b)
end