-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathButton.cpp
More file actions
100 lines (80 loc) · 2.14 KB
/
Button.cpp
File metadata and controls
100 lines (80 loc) · 2.14 KB
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
#include "Button.hpp"
using namespace gui;
Button::Button(const sf::Texture &texture,
const sf::IntRect &texRectNormal,
const sf::IntRect &texRectFocused)
: mTexRectNormal(texRectNormal),
mTexRectFocused(texRectFocused),
mTexRectClicked(texRectFocused),
mSprite(texture),
mOldMouseButtonState(false),
mIsVisible(true),
mHasStartedClick(false),
mEnable(true)
{
}
Button::Button(const sf::Texture &texture,
const sf::IntRect &texRectNormal,
const sf::IntRect &texRectFocused,
const sf::IntRect &texRectClicked)
: mTexRectNormal(texRectNormal),
mTexRectFocused(texRectFocused),
mTexRectClicked(texRectClicked),
mSprite(texture),
mOldMouseButtonState(false),
mIsVisible(true),
mHasStartedClick(false),
mEnable(true)
{
}
void Button::setPosition(const sf::Vector2f &position)
{
mSprite.setPosition(position);
}
void Button::setVisible(bool visible)
{
mIsVisible = visible;
}
void Button::setEnable(bool enable)
{
mEnable = enable;
mSprite.setTextureRect(mTexRectNormal);
if (mEnable)
mSprite.setColor(sf::Color::White);
else
mSprite.setColor(sf::Color(255,255,255,172));
}
bool Button::update(sf::Vector2f mousePosition, bool mouseButtonPressed)
{
if (!mIsVisible || !mEnable)
return mHasStartedClick = false;
bool isFocusing = mSprite.getGlobalBounds().contains(mousePosition);
// compute new display
if (isFocusing) {
if (mouseButtonPressed && mHasStartedClick)
mSprite.setTextureRect(mTexRectClicked);
else
mSprite.setTextureRect(mTexRectFocused);
} else
mSprite.setTextureRect(mTexRectNormal);
// test if user clicked
bool hasClicked(false);
if (isFocusing) {
if (mouseButtonPressed && !mOldMouseButtonState)
mHasStartedClick = true;
else if (!mouseButtonPressed && mOldMouseButtonState && mHasStartedClick) {
hasClicked = true;
mHasStartedClick = false;
}
} else {
if (mouseButtonPressed != mOldMouseButtonState)
mHasStartedClick = false;
}
mOldMouseButtonState = mouseButtonPressed;
return hasClicked;
}
void Button::draw(sf::RenderTarget &target, sf::RenderStates states) const
{
if (mIsVisible)
target.draw(mSprite);
}