-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathPlayer.js
74 lines (65 loc) · 1.63 KB
/
Player.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
export default class Player {
rightPressed = false;
leftPressed = false;
shootPressed = false;
constructor(canvas, velocity, bulletController) {
this.canvas = canvas;
this.velocity = velocity;
this.bulletController = bulletController;
this.x = this.canvas.width / 2;
this.y = this.canvas.height - 75;
this.width = 50;
this.height = 48;
this.image = new Image();
this.image.src = "images/player.png";
document.addEventListener("keydown", this.keydown);
document.addEventListener("keyup", this.keyup);
}
draw(ctx) {
if (this.shootPressed) {
this.bulletController.shoot(this.x + this.width / 2, this.y, 4, 10);
}
this.move();
this.collideWithWalls();
ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
}
collideWithWalls() {
//left
if (this.x < 0) {
this.x = 0;
}
//right
if (this.x > this.canvas.width - this.width) {
this.x = this.canvas.width - this.width;
}
}
move() {
if (this.rightPressed) {
this.x += this.velocity;
} else if (this.leftPressed) {
this.x += -this.velocity;
}
}
keydown = (event) => {
if (event.code == "ArrowRight") {
this.rightPressed = true;
}
if (event.code == "ArrowLeft") {
this.leftPressed = true;
}
if (event.code == "Space") {
this.shootPressed = true;
}
};
keyup = (event) => {
if (event.code == "ArrowRight") {
this.rightPressed = false;
}
if (event.code == "ArrowLeft") {
this.leftPressed = false;
}
if (event.code == "Space") {
this.shootPressed = false;
}
};
}