-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
64 lines (50 loc) · 1.88 KB
/
app.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
let playerState = "idle";
const canvas = document.querySelector("#canvas1");
const ctx = canvas.getContext('2d');
const canvasWidth = canvas.width = 600;
const canvasHeight = canvas.height = 600;
const spriteWidth = 575;
const spriteHeight = 523;
const playerImage = new Image();
playerImage.src = 'shadow_dog.png';
const spriteAnimations = [
{name:'idle', frames:7 } ,
{name:'jump', frames:7 } ,
{name:'fall', frames:7 } ,
{name:'run', frames:9 } ,
{name:'dizzy', frames:11 } ,
{name:'sit', frames:5 } ,
{name:'roll', frames:7 } ,
{name:'bite', frames:7 } ,
{name:'ko', frames:12 } ,
{name:'getHit', frames:4 }
];
spriteAnimations.forEach((el, index)=>{
el.location = [];
for (let i = 0; i < el.frames; i++) {
let loc = {};
loc.X = i*spriteWidth;
loc.Y = index*spriteHeight;
el.location.push(loc);
}
})
let index = spriteAnimations.findIndex((spriteAnimations) => spriteAnimations.name===playerState);
//This is an arrow function where we aren't using {} because if we do, the we need to explicitly return true or false
let frame = spriteAnimations[index];
const dropDown = document.querySelector("#animations");
dropDown.addEventListener('change', (event)=>{
playerState = event.target.value;
index = spriteAnimations.findIndex((spriteAnimations) => spriteAnimations.name===playerState);
frame = spriteAnimations[index];
})
let gameFrame = 0;
let position = 0;
const staggerFrames = 7;
function animate() {
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
position = Math.floor(gameFrame / staggerFrames) % frame.frames;
ctx.drawImage(playerImage, frame.location[position].X, frame.location[position].Y, spriteWidth, spriteHeight, 0, 0, spriteWidth, spriteHeight);
gameFrame++;
requestAnimationFrame(animate);
};
animate();