-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathblob.js
108 lines (89 loc) · 2.78 KB
/
blob.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
BLOB_CIRCLE = 'CIRCLE';
BLOB_RECT = 'RECT';
// Jumping event states
JUMPING_NOT = 'JUMPING_NOT'
JUMPING_ASCEND = 'JUMPING_ASCEND'
JUMPING_DESCEND = 'JUMPING_DESCEND'
function drawRect(topLeftX, topLeftY, boxWidth, boxHeight, fillColor) {
ctx.beginPath();
ctx.fillStyle = fillColor;
ctx.fillRect(topLeftX,topLeftY, boxWidth,boxHeight);
ctx.closePath();
}
class Blob {
constructor(type, x=W/2, y=H/2, w=20, h=20, color='black') {
this.space = {
x,
y,
w,
h
}
this.col = color;
this.speed = {
dx: 0,
dy: 0
}
this.type = type;
if (this.type == BLOB_CIRCLE)
this.space.rad = this.space.w
this.events = {
jumping: {
status: JUMPING_NOT,
speed: 20
}
}
}
modulo() {
this.space.x = Math.min(this.space.x, W-this.space.w);
this.space.y = Math.min(this.space.y, H-this.space.h);
this.space.x = Math.max(0, this.space.x);
this.space.y = Math.max(0, this.space.y);
if(this.space.y + this.space.h == H)
this.on_rest();
}
update() {
this.space.x += this.speed.dx;
this.space.y += this.speed.dy;
this.speed.dy += 1
this.modulo();
this.draw();
}
draw() {
if (this.type == BLOB_CIRCLE)
drawCircle(this.space.x, this.space.y, this.space.rad, this.col);
else
drawRect(this.space.x, this.space.y, this.space.w, this.space.h, this.col);
}
keyDownHandler(e) {
let code = e.keyCode;
switch (code) {
case 37: this.speed.dx = -10; break; //Left key
// case 38: this.speed.dy = -10; break; //Up key
case 39: this.speed.dx = 10; break; //Right key
// case 40: this.speed.dy = 10; break; //Down key
case 32: { //Space key
if (this.events.jumping.status != JUMPING_NOT)
break;
this.events.jumping.status = JUMPING_ASCEND;
this.speed.dy = -this.events.jumping.speed;
break;
}
default: console.log(code); //Everything else
}
}
keyUpHandler(e) {
let code = e.keyCode;
switch (code) {
case 37: this.speed.dx = 0; break; //Left key
// case 38: this.speed.dy = 0; break; //Up key
case 39: this.speed.dx = 0; break; //Right key
// case 40: this.speed.dy = 0; break; //Down key
case 32: break; //Space key
default: console.log(code); //Everything else
}
}
on_rest() {
this.speed.dy = 0;
this.events.jumping.status = JUMPING_NOT;
}
}