This repository has been archived by the owner on Dec 27, 2018. It is now read-only.
/
chaser.js
72 lines (60 loc) · 1.66 KB
/
chaser.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
var inherits = require('inherits')
, Entity = require('./entity')
, imageloaded = require('image-loaded')
, game
, id = 0
module.exports = Chaser
var sprite = new Image
sprite.src = 'chaser.png'
function Chaser(pos, spd, acc) {
if (!(this instanceof Chaser)) return new Chaser(pos, spd, acc)
Entity.call(this)
if (!game) throw new Error('game not ready')
var self = this
game.chasers.boids.push(this.data = {
spd: this.spd = spd || [0,0]
, pos: this.pos = pos || [0,0]
, acc: this.acc = acc || [0,0]
, id: this.id = id++
})
this.pos[2] = 16
this.pos[3] = -15
game.boids.attractors.push(this.pos)
this.dying = false
this.scale = 1
this.once('kill', function() {
var idx = game.boids.attractors.indexOf(self.pos)
if (idx !== -1) game.boids.attractors.splice(idx, 1)
idx = game.chasers.boids.indexOf(self.data)
if (idx !== -1) return game.chasers.boids.splice(idx, 1)
for (var i = 0, l = game.chasers.boids.length; i < l; i += 1) {
if (game.chasers.boids[i].id === self.id) {
return game.chasers.boids.splice(i, 1)
}
}
})
}
inherits(Chaser, Entity)
Chaser.register = function(g) {
game = g
}
Chaser.prototype.tick = function() {
if (this.dying) this.scale -= 0.05
if (this.scale < 0) {
this.scale = 0
this.dying = false
this.kill()
}
}
Chaser.prototype.render = function(ctx, manager) {
var camera = manager.first('camera')
if (this.scale !== 1) {
ctx.save()
ctx.translate(this.pos[0], this.pos[1])
ctx.scale(this.scale, this.scale)
ctx.drawImage(sprite, -16, -16)
ctx.restore()
} else {
ctx.drawImage(sprite, this.pos[0]-16, this.pos[1]-16)
}
}