/
Sprite_Button.js
108 lines (94 loc) · 2.65 KB
/
Sprite_Button.js
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
99
100
101
102
103
104
105
106
107
108
//-----------------------------------------------------------------------------
// Sprite_Button
//
// The sprite for displaying a button.
function Sprite_Button() {
this.initialize.apply(this, arguments);
}
Sprite_Button.prototype = Object.create(Sprite.prototype);
Sprite_Button.prototype.constructor = Sprite_Button;
Sprite_Button.prototype.initialize = function() {
Sprite.prototype.initialize.call(this);
this._touching = false;
this._coldFrame = null;
this._hotFrame = null;
this._clickHandler = null;
};
Sprite_Button.prototype.update = function() {
Sprite.prototype.update.call(this);
this.updateFrame();
this.processTouch();
};
Sprite_Button.prototype.updateFrame = function() {
var frame;
if (this._touching) {
frame = this._hotFrame;
} else {
frame = this._coldFrame;
}
if (frame) {
this.setFrame(frame.x, frame.y, frame.width, frame.height);
}
};
Sprite_Button.prototype.setColdFrame = function(x, y, width, height) {
this._coldFrame = new Rectangle(x, y, width, height);
};
Sprite_Button.prototype.setHotFrame = function(x, y, width, height) {
this._hotFrame = new Rectangle(x, y, width, height);
};
Sprite_Button.prototype.setClickHandler = function(method) {
this._clickHandler = method;
};
Sprite_Button.prototype.callClickHandler = function() {
if (this._clickHandler) {
this._clickHandler();
}
};
Sprite_Button.prototype.processTouch = function() {
if (this.isActive()) {
if (TouchInput.isTriggered() && this.isButtonTouched()) {
this._touching = true;
}
if (this._touching) {
if (TouchInput.isReleased() || !this.isButtonTouched()) {
this._touching = false;
if (TouchInput.isReleased()) {
this.callClickHandler();
}
}
}
} else {
this._touching = false;
}
};
Sprite_Button.prototype.isActive = function() {
var node = this;
while (node) {
if (!node.visible) {
return false;
}
node = node.parent;
}
return true;
};
Sprite_Button.prototype.isButtonTouched = function() {
var x = this.canvasToLocalX(TouchInput.x);
var y = this.canvasToLocalY(TouchInput.y);
return x >= 0 && y >= 0 && x < this.width && y < this.height;
};
Sprite_Button.prototype.canvasToLocalX = function(x) {
var node = this;
while (node) {
x -= node.x;
node = node.parent;
}
return x;
};
Sprite_Button.prototype.canvasToLocalY = function(y) {
var node = this;
while (node) {
y -= node.y;
node = node.parent;
}
return y;
};