1 | "use strict";
|
2 |
|
3 | var Animation = require("./animation");
|
4 |
|
5 | function Button(mouse, x, y, sprites, stateChanged) {
|
6 | this.mouse = mouse;
|
7 | this.x = x;
|
8 | this.y = y;
|
9 | this.state = "normal";
|
10 | this.stateChanged = stateChanged;
|
11 | this.isToggle = false;
|
12 |
|
13 | if (!sprites.normal && sprites.pressDown instanceof Animation) {
|
14 | sprites.normal = sprites.pressDown.frames[0].img;
|
15 | }
|
16 | if (!sprites.pressed && sprites.pressDown instanceof Animation) {
|
17 | sprites.pressed = sprites.pressDown.frames[sprites.pressDown.frames.length - 1].img;
|
18 | }
|
19 | this.sprites = sprites;
|
20 | if (!sprites.normal) {
|
21 | console.error("Button is missing the required \"normal\" sprite");
|
22 | }
|
23 | if (!sprites.pressed) {
|
24 | console.error("Button is missing the required \"pressed\" sprite");
|
25 | }
|
26 |
|
27 | this.width = sprites.normal.width;
|
28 | this.height = sprites.normal.height;
|
29 | }
|
30 | Button.prototype.move = function(elapsedMillis) {
|
31 | var self = this;
|
32 | function changeState(state) {
|
33 | self.state = state;
|
34 | self.stateChanged(state);
|
35 | if (self.sprites[state] instanceof Animation) {
|
36 | self.sprites[state].reset();
|
37 | }
|
38 | }
|
39 |
|
40 | if (this.state === "normal" && this.mouse.consumePressed(0, this.x, this.y, this.width, this.height)) {
|
41 | changeState("pressDown");
|
42 | if (!this.sprites.pressDown) {
|
43 | changeState("pressed");
|
44 | }
|
45 | }
|
46 | if (this.state === "pressDown" && this.sprites.pressDown.frame === this.sprites.pressDown.frames.length - 1) {
|
47 | changeState("pressed");
|
48 | }
|
49 | if (this.state === "pressed" && (this.isToggle ? this.mouse.consumePressed(0, this.x, this.y, this.width, this.height) : !this.mouse.isPressed(0))) {
|
50 | changeState("popUp");
|
51 | if (!this.sprites.popUp) {
|
52 | changeState("normal");
|
53 | }
|
54 | }
|
55 | if (this.state === "popUp" && this.sprites.popUp.frame === this.sprites.popUp.frames.length - 1) {
|
56 | changeState("normal");
|
57 | }
|
58 |
|
59 | var sprite = this.sprites[this.state];
|
60 | if (typeof sprite.move === "function") {
|
61 | sprite.move(elapsedMillis);
|
62 | }
|
63 | };
|
64 | Button.prototype.draw = function(context) {
|
65 | var sprite = this.sprites[this.state];
|
66 | if (typeof sprite.draw === "function") {
|
67 | sprite.draw(context, this.x, this.y);
|
68 | } else {
|
69 | context.drawImage(sprite, this.x, this.y);
|
70 | }
|
71 | };
|
72 |
|
73 | module.exports = Button;
|