-
Notifications
You must be signed in to change notification settings - Fork 21
/
Sprite.js
144 lines (128 loc) · 2.8 KB
/
Sprite.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
/**
* The Sprite class represents a simple animated character for a game
* @name Sprite
* @constructor Sprite
*/
class Sprite {
constructor(options = {}){
/**
* The x position of the sprite in pixels
* @type {Number}
* @memberOf Sprite#
* @default
*/
this.x = 0.0;
/**
* The y position of the sprite in pixels
* @type {Number}
* @memberOf Sprite#
* @default
*/
this.y = 0.0;
/**
* The x component of the velocity in pixels per second
* @type {Number}
* @memberOf Sprite#
* @default
*/
this.dx = 0.0;
/**
* The y component of the velocity in pixels per second
* @type {Number}
* @memberOf Sprite#
* @default
*/
this.dy = 0.0;
/**
* The max speed a sprite can move in either direction
* @type {Number}
* @memberOf Sprite#
* @default
*/
this.maxSpeed = 0.0;
/**
* The name of this Sprite
* @type {String}
* @memberOf Sprite#
* @default
*/
this.name = null;
/**
* The radius of this sprite in pixels for simple collision detection
* @type {Number}
* @memberOf Sprite#
* @default
*/
this.collisionRadius = 40;
Object.assign(this, options);
}
/**
* Updates this Sprite's Animation and its position based on the velocity.
* @function
* @memberOf Sprite#
* @param {Number} elapsedTime The elapsed time in milliseconds since the previous update
*/
update(elapsedTime){
this.x += this.dx * elapsedTime;
this.y += this.dy * elapsedTime;
this.anim.update(elapsedTime);
}
/**
* Returns the maxSpeed up to the speed limit
* @function
* @memberOf Sprite#
* @param {Number} v Speed limit
* @return {Number} maxSpeed up to speed limit
*/
limitSpeed(v){
if(this.maxSpeed){
if(Math.abs(v) > this.maxSpeed){
if(v > 0){
return this.maxSpeed;
}else if(v < 0){
return this.maxSpeed;
}else{
return 0;
}
}else{
return v;
}
}else{
return v;
}
}
/**
* Gets this Sprite's current animation frame.
* @function
* @memberOf Sprite#
* @return {AnimationFrame} The current frame of the Animation
*/
getCurrentFrame(){
if(this.anim){
return this.anim.getCurrentFrame();
}
}
/**
* Draws the sprite
* @function
* @memberOf Sprite#
* @param {Context} context The HTML5 drawing context
*/
draw(context){
if(this.anim){
this.anim.draw(context, this.x, this.y);
}
}
/**
* Clones the instance of Sprite it is called upon
* @function
* @memberOf Sprite#
* @return {Sprite} A clone of the Sprite
*/
clone() {
return new Sprite({
anim: this.anim.clone()
});
}
}
module.exports = Sprite;