generated from tassaron/canvas-game
-
Notifications
You must be signed in to change notification settings - Fork 0
/
thing.js
80 lines (65 loc) · 2.15 KB
/
thing.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
export class Thing {
constructor(x, y, width, height, src=null) {
this._x = x;
this._y = y;
this.width = width;
this.height = height;
this.src = src;
}
get x() {return this._x}
set x(i) {this._x = i}
get y() {return this._y}
set y(i) {this._y = i}
update(ratio, keyboard, mouse) {}
draw(ctx, drawSprite) {
if (this.src == null) {return}
drawSprite[this.src](this.x, this.y);
}
collides(other) {
return (this.x + this.width > other.x && this.x < other.x + other.width && other.y + other.height > this.y && other.y < this.y + this.height);
}
}
export class AnimatedThing extends Thing {
constructor(x, y, width, height, src, animFrames, animTiming) {
super(x, y, width, height, src);
this.animFrames = animFrames;
this.animTiming = animTiming;
this.anim = 0.0;
this.loops = 0;
}
update(ratio, keyboard, mouse) {
this.anim += ratio;
if (this.anim > this.animFrames * this.animTiming) {this.anim = 0.0; this.loops++;}
}
draw(ctx, drawSprite) {
let frame = Math.floor(this.anim / this.animTiming);
drawSprite[this.src](frame, this.x, this.y);
}
}
export class ClickableThing extends Thing {
constructor(x, y, width, height, src=null) {
super(x, y, width, height, src);
this.cooldown = 0.0;
this.delay = 30.0;
}
update(ratio, keyboard, mouse, func=this.leftClicked, self=this) {
if (mouse.leftClick && this.cooldown == 0.0 && this.collides(mouse)) {
func(self);
this.cooldown = this.delay;
} else if (this.cooldown < 0.0) {
this.cooldown = 0.0;
} else if (this.cooldown > 0.0) {
this.cooldown -= ratio;
}
}
draw(ctx, drawSprite) {
if (this.src == null) {return}
drawSprite[this.src](this.x, this.y);
}
leftClicked() {
console.log("clicked");
}
collides(other) {
return (this.x + this.width > other.x && this.x < other.x + other.width && other.y + other.height > this.y && other.y < this.y + this.height);
}
}