-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
102 lines (86 loc) · 2.63 KB
/
index.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
let c = document.getElementById('win-canvas');
let ctx = c.getContext('2d');
let load_img = (src, callback) => {
let img = document.createElement('img');
img.onload = () => callback(img);
img.src = src;
};
let img_path = (anim, f_num) => {
return 'images/' + anim + '/' + f_num + '.png';
};
anims_dict = {
idle: [1, 2, 3, 4, 5, 6, 7, 8],
kick: [1, 2, 3, 4, 5, 6, 7],
punch: [1, 2, 3, 4, 5, 6, 7],
backward: [1, 2, 3, 4, 5, 6],
block: [1, 2, 3, 4, 5, 6, 7, 8, 9],
forward: [1, 2, 3, 4, 5, 6],
};
let load_frames = (callback) => {
let frames = {
idle: [],
kick: [],
punch: [],
backward: [],
block: [],
forward: [],
};
let frames_to_load = 0;
['idle', 'kick', 'punch', 'forward', 'block', 'backward'].forEach(
(animation) => {
let animatedFrames = anims_dict[animation];
frames_to_load += animatedFrames.length;
animatedFrames.forEach((frameNumber) => {
let path = img_path(animation, frameNumber);
load_img(path, (image) => {
frames[animation][frameNumber - 1] = image;
frames_to_load -= 1;
if (frames_to_load === 0) {
callback(frames);
}
});
});
}
);
};
let animate = (ctx, images, animation, callback) => {
images[animation].forEach((image, index) => {
setTimeout(() => {
ctx.clearRect(0, 0, c.width, c.height);
ctx.drawImage(image, 0, 0, c.width, c.height);
}, index * 100);
});
setTimeout(callback, images[animation].length * 100);
};
load_frames((images) => {
let animationQueue = [];
let aux = () => {
let selectedAnimation = '';
if (animationQueue.length === 0) selectedAnimation = 'idle';
else selectedAnimation = animationQueue.shift();
animate(ctx, images, selectedAnimation, aux);
};
aux();
document.getElementById('forward').addEventListener('click', () => {
animationQueue.push('forward');
});
document.getElementById('backward').addEventListener('click', () => {
animationQueue.push('backward');
});
document.getElementById('block').addEventListener('click', () => {
animationQueue.push('block');
});
document.getElementById('kick').onclick = () => {
animationQueue.push('kick');
};
document.getElementById('punch').onclick = () => {
animationQueue.push('punch');
};
document.addEventListener('keydown', function (event) {
if (event.key === 'd') animationQueue.push('forward');
else if (event.key === 'a') animationQueue.push('backward');
else if (event.key === 'w') animationQueue.push('punch');
else if (event.key === 's') animationQueue.push('kick');
else if (event.code === 'Space') animationQueue.push('block');
});
});