-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
bullet.js
73 lines (56 loc) · 1.55 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
var inherits = require('inherits');
var aabb = require('aabb-2d');
var Entity = require('crtrdg-entity');
module.exports = Bullet;
inherits(Bullet, Entity);
function Bullet(options){
this.size = {
x: 6,
y: 6
};
this.target = {
x: options.target.x,
y: options.target.y
}
this.position = {
x: options.position.x - this.size.x / 2,
y: options.position.y - this.size.y / 2
};
this.velocity = {
x: 0,
y: 0
};
this.dx = (this.target.x - this.position.x);
this.dy = (this.target.y - this.position.y);
this.mag = Math.sqrt(this.dx * this.dx + this.dy * this.dy);
this.speed = 8;
this.color = '#fff';
this.boundingBox = aabb([this.position.x, this.position.y], [this.size.x, this.size.y]);
this.on('update', function(interval){
this.boundingBox = aabb([this.position.x, this.position.y], [this.size.x, this.size.y]);
this.velocity.x = (this.dx / this.mag) * this.speed;
this.velocity.y = (this.dy / this.mag) * this.speed;
this.position.x += this.velocity.x;
this.position.y += this.velocity.y;
this.checkBoundaries();
});
this.on('draw', function(context){
context.fillStyle = this.color;
context.fillRect(this.position.x, this.position.y, this.size.x, this.size.y);
});
return this;
}
Bullet.prototype.checkBoundaries = function(){
if (this.position.x < 0){
this.remove();
}
if (this.position.x > this.game.width){
this.remove();
}
if (this.position.y < 0){
this.remove();
}
if (this.position.y > this.game.height){
this.remove();
}
};