Repository navigation
Expand file tree
/
Copy pathPlayer.js
More file actions
75 lines (64 loc) · 2.26 KB
/
Copy pathPlayer.js
File metadata and controls
75 lines (64 loc) · 2.26 KB
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
export default class Player {
rightPressed = false;
leftPressed = false;
shootPressed = false;
constructor(canvas, velocity, bulletController) { //, frameIndex
this.canvas = canvas;
this.velocity = velocity;
this.bulletController = bulletController;
this.width = 50; //Image dimension
this.height = 48; //Idem
this.x = (this.canvas.width / 2) - (this.width / 2); //Starting position in the middle of the screen
this.y = this.canvas.height - 75; //Slight pop-off the bottom
this.image = new Image();
this.image.src = "images/player.png"; //${frameIndex}
document.addEventListener("keydown", this.keydown); //All lower case
document.addEventListener("keyup", this.keyup);
}
draw(ctx) {
if (this.shootPressed) {
//console.log("shoot");
this.bulletController.shoot(this.x + (this.width / 2), this.y, 4, 10); //(X, Y, speed, time gap)
}
this.move();
this.collideWithWalls();
ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
}
collideWithWalls() {
if (this.x < 0) { //Left boundary
this.x = 0; //Prevents x from getting smaller than 0
}
if (this.x > this.canvas.width - this.width) { //Right boundary
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 => { //Needs to be in arrow function format for the this proprety to function correctly
if (event.code == "ArrowRight") { // || "D"
this.rightPressed = true;
}
if (event.code == "ArrowLeft") { // || "Q"
this.leftPressed = true;
}
if (event.code == "Space") {
this.shootPressed = true;
}
};
keyup = event => {
if (event.code == "ArrowRight") { // || "D"
this.rightPressed = false;
}
if (event.code == "ArrowLeft") { // || "Q"
this.leftPressed = false;
}
if (event.code == "Space") {
this.shootPressed = false;
}
};
}