-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbullet.js
81 lines (70 loc) · 2.1 KB
/
bullet.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
;(function(exports) {
function Bullet(center, angle, creator) {
this.creator = creator;
this.game = creator.game;
this.color = creator.color;
this.created = Date.now();
this.isEnemy = creator.isEnemy;
this.isDead = false;
this.angle = angle;
this.speed = 5;
// Set points and lines about bullet center.
this.center = { x: center.x, y: center.y };
this.resetPoints();
this.resetLineSegments();
}
Bullet.prototype = {
/**
* Updates position of the bullet.
*/
update: function() {
// Move center by speed and angle.
this.game.trig.translatePoint(this.center, this.speed, this.angle);
// Reset points and lines about new center.
this.resetPoints();
this.resetLineSegments();
// Kill off-screen bullets.
if (this.game.offScreen(this)) {
this.die();
}
},
/**
* Draws the bullet on the screen.
*/
draw: function(screen) {
screen.strokeStyle = this.color;
screen.beginPath();
screen.arc(this.center.x, this.center.y, 1, 0, this.game.FULL_ROTATION);
screen.stroke();
},
/**
* Handles events occurring upon the destruction of the bullet.
*/
die: function() {
// Ensure the bullet is removed at most once.
if (this.isDead) return;
this.isDead = true;
// Remove the dead bullet from the list of game bodies.
this.game.removeBody(this);
},
/**
* Resets the points of the path of the bullet between time t-1 and t,
* relative to its center.
*/
resetPoints: function() {
this.points = [
{ x: this.center.x - this.speed * Math.cos(this.angle),
y: this.center.y - this.speed * -Math.sin(this.angle) },
{ x: this.center.x, y: this.center.y }
];
},
/**
* Resets the line segment of the path of the bullet between time t-1 and t,
* relative to its points. Used for collision detection.
*/
resetLineSegments: function() {
this.lineSegments = [{ p1: this.points[0], p2: this.points[1] }];
}
};
exports.Bullet = Bullet;
})(this);