-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmeteor.js
103 lines (93 loc) · 3.1 KB
/
meteor.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
MeteorImg = new Image();
MeteorImg.src = 'images/meteor.png'
meteors = new Array()
PlanetImg = new Image();
PlanetImg.src = 'images/planet.png'
function Meteor(canvasCtx, space, type, prevX){
this.canvasCtx = canvasCtx
this.xPos = 0;
this.yPos = 0;
this.dX = 0;
this.dY = 0;
this.type = type;
this.prevX = prevX;
this.planetSize = 60;
this.nImage = 0;
this.imgWidth = 40;
this.imgHeight = 60;
this.frameCount = 0;
this.frameLoopCycle = 15;
this.space = space;
this.init()
}
Meteor.prototype = {
init: function() {
this.imgSprite = MeteorImg;
//prevent 2 meteors from spawning together and make spawn distribution pseudo triangular with mean at center
while (Math.abs(this.xPos - this.prevX) < 25 || this.xPos == 0) {
this.xPos = Math.floor(Math.random() * (this.canvasCtx.canvas.width - 10) + 5);
var xBias = Math.random() * (this.canvasCtx.canvas.width/4);
this.xPos += this.xPos > this.canvasCtx.canvas.width/2 ? -xBias : xBias;
}
this.yPos = -this.imgSprite.height - 10; // Meteor should start off of the screen
this.radius = this.imgWidth/4;
this.dX = 0;
switch (this.type) {
case -2:
this.dY = 2.5;
this.xPos = this.space.Game.Player.charX - 10 + Math.random() * 20;
break;
case -1:
this.dY = 2.5;
this.xPos = this.space.Game.Player.charX;
break;
case 0:
this.dY = 2.5;
break;
case 1:
this.dY = 4;
break;
case 2:
this.dY = 5.5;
break;
case 3:
this.dX = Math.random() > 0.5 ? -1.0 : 1.0;
this.dY = 4;
break;
case 4:
this.dY = 5.5;
this.xPos = this.space.Game.Player.charX - 10 + Math.random() * 40;
break;
case 5:
this.dX = Math.random() > 0.5 ? -1.5 : 1.5;
this.dY = 4;
this.xPos = this.space.Game.Player.charX - 10 + Math.random() * 40;
break;
}
this.draw();
meteors.push(this);
},
draw: function() {
this.canvasCtx.drawImage(MeteorImg, this.nImage * this.imgWidth, 0, this.imgWidth, this.imgHeight, this.xPos, this.yPos, this.imgWidth, this.imgHeight);
if (this.frameCount % this.frameLoopCycle == 0) {
this.nImage++;
}
if (this.nImage > 3) {
this.nImage = 0;
}
},
update: function(frameCount) {
this.frameCount = frameCount
if(inCtxBounds(this.imgSprite, this.xPos, this.yPos, this.canvasCtx)){
this.xPos += this.dX
this.yPos += this.dY
this.draw()
} else {
this.space.removeMeteor(this);
}
}
}
function inCtxBounds(img, x, y, ctx){
return x > 0 - img.width && x < ctx.canvas.width + img.width
&& y < ctx.canvas.height + img.height;
}