-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sprite.js
executable file
·94 lines (69 loc) · 2.54 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
// ============
// SPRITE STUFF
// ============
"use strict";
/* jshint browser: true, devel: true, globalstrict: true */
/*
0 1 2 3 4 5 6 7 8
12345678901234567890123456789012345678901234567890123456789012345678901234567890
*/
// Construct a "sprite" from the given `image`,
//
function Sprite(image, scale, sheetCoords) {
this.image = image;
this.sheetCoords = sheetCoords;
this.scale = scale;
this.setAnimation("default");
this.width = this.activeAnimation.size.w * this.scale;
this.height = this.activeAnimation.size.h * this.scale;
}
Sprite.prototype.scale = g_scale;
Sprite.prototype.nextFrame = function () {
this.frame = (this.frame + 1) % this.numFrames;
};
Sprite.prototype.setAnimation = function (name) {
this.activeAnimation = this.sheetCoords[name];
this.numFrames = this.activeAnimation.frames.length;
this.width = this.activeAnimation.size.w * this.scale;
this.height = this.activeAnimation.size.h * this.scale;
this.frame = 0;
};
Sprite.prototype.drawAt = function (ctx, x, y) {
ctx.drawImage(this.image,
x, y);
};
Sprite.prototype.drawCentredAt = function (ctx, cx, cy, rotation) {
if (rotation === undefined) rotation = 0;
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(rotation);
ctx.scale(this.scale, this.scale);
// drawImage expects "top-left" coords, so we offset our destination
// coords accordingly, to draw our sprite centred at the origin
const {w, h} = this.activeAnimation.size;
let [sx, sy] = this.activeAnimation.frames[this.frame];
ctx.drawImage(this.image,
sx, sy,
w, h,
-w/2, -h/2,
w, h);
ctx.restore();
};
Sprite.prototype.drawWrappedCentredAt = function (ctx, cx, cy, rotation) {
// Get "screen width"
var sw = g_canvas.width;
// Draw primary instance
this.drawWrappedVerticalCentredAt(ctx, cx, cy, rotation);
// Left and Right wraps
this.drawWrappedVerticalCentredAt(ctx, cx - sw, cy, rotation);
this.drawWrappedVerticalCentredAt(ctx, cx + sw, cy, rotation);
};
Sprite.prototype.drawWrappedVerticalCentredAt = function (ctx, cx, cy, rotation) {
// Get "screen height"
var sh = g_canvas.height;
// Draw primary instance
this.drawCentredAt(ctx, cx, cy, rotation);
// Top and Bottom wraps
this.drawCentredAt(ctx, cx, cy - sh, rotation);
this.drawCentredAt(ctx, cx, cy + sh, rotation);
};