/
button.go
98 lines (82 loc) · 1.8 KB
/
button.go
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package ui
import (
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/inpututil"
"github.com/hajimehoshi/ebiten/v2/vector"
"golang.org/x/image/font"
"github.com/mymmrac/battleship/core"
"github.com/mymmrac/battleship/data"
)
const buttonPadding float32 = 4
type Button struct {
core.BaseGameObject
pos data.Point[float32]
width float32
height float32
text string
fontFace font.Face
hover bool
clicked bool
}
func NewButton(pos data.Point[float32], width float32, height float32, text string, fontFace font.Face) *Button {
return &Button{
BaseGameObject: core.NewBaseGameObject(),
pos: pos,
width: width,
height: height,
text: text,
fontFace: fontFace,
}
}
func (b *Button) Update(cp data.Point[float32]) {
b.hover = b.pos.X <= cp.X && cp.X <= b.pos.X+b.width &&
b.pos.Y <= cp.Y && cp.Y <= b.pos.Y+b.height
b.clicked = b.hover && inpututil.IsMouseButtonJustPressed(ebiten.MouseButtonLeft)
}
func (b *Button) Disable() {
b.hover = false
b.clicked = false
b.BaseGameObject.Disable()
}
func (b *Button) CursorPointer() bool {
return b.hover
}
func (b *Button) Clicked() bool {
return b.clicked
}
func (b *Button) Draw(screen *ebiten.Image) {
// Border
clr := BorderColor
if !b.Active() {
clr = MutedColor
}
vector.StrokeRect(
screen,
b.pos.X,
b.pos.Y,
b.width,
b.height,
2,
clr,
)
// Background
if b.hover {
vector.DrawFilledRect(
screen,
b.pos.X+buttonPadding,
b.pos.Y+buttonPadding,
b.width-buttonPadding*2,
b.height-buttonPadding*2,
MutedColor,
)
}
// Text
clr = TextLightColor
if b.hover {
clr = TextDarkColor
}
if !b.Active() {
clr = MutedColor
}
DrawCenteredText(screen, b.fontFace, b.text, int(b.pos.X+b.width/2), int(b.pos.Y+b.height/2), clr)
}