-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrender.js
70 lines (53 loc) · 2.17 KB
/
render.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
var lastCreaturePosition = [0,0,0,0];
// renders the game
function render(time, screen, meters, sprite) {
var creature = getCreature();
// updates the meters showing the creature's needs
updateMeters(meters, creature.stats)
// clear where the creature was located last render
screen.fillRect(...lastCreaturePosition);
// draw the creature at their new position
lastCreaturePosition = drawCreature(screen, time, creature, sprite);
}
// update meters from creature statistics
function updateMeters(meters, stats) {
meters.energy.value = stats.energy;
meters.stomach.value = stats.stomach;
// this can be really slow, so it only updates when the creature's name changes.
if(meters.name.innerText !== stats.name) {
meters.name.innerText = stats.name;
}
if(meters.pronouns.innerText !== stats.pronouns) {
meters.pronouns.innerText = stats.pronouns;
}
}
// draws a creature into the context
function drawCreature(screen, time, creature, sprite) {
const { position: [x, y], animation } = creature;
// look up the frame to draw
const animationFrame = getAnimationFrame(time, sprite.animations[animation]);
const [,, sprite_w, sprite_h] = animationFrame;
const creaturePosition = [x, y, sprite_w * 2, sprite_h * 2];
// draw the frame
screen.drawImage(sprite.sheet, ...animationFrame, ...creaturePosition);
return creaturePosition;
}
// `gameFrame` is a number saying how many times we've animated before.
// `animation` contains pixel coordinatess into the sprite sheet in [x, y] pairs.
function getAnimationFrame(gameFrame, animation) {
// identifies the frame we're trying to render in the animation loop
const animationFrame = gameFrame % animation.totalTime;
// index into the animation frame & time arrays
let index = 0;
// total time accumulated by the frame scan
let frameTime = 0;
// the frame to render
let frame = null;
// scan the frames to find the one to render
do {
frame = animation.frames[index];
frameTime += animation.time[index];
index++;
} while(frameTime < animationFrame);
return frame || animation.frames[0];
}