-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
111 lines (97 loc) · 2.18 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
103
104
105
106
107
108
109
110
111
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 500;
const keys = [];
const player = {
x: 0,
y: 0,
width: 32,
height: 48,
// width: 50,
// height: 48,
frameX: 0,
frameY: 0,
speed: 10,
moving: false,
};
const playerSprite = new Image();
playerSprite.src = './images/darthvader.png';
const drawSprite = (img, sX, sY, sW, sH, dX, dY, dW, dH) => {
ctx.drawImage(img, sX, sY, sW, sH, dX, dY, dW, dH);
};
const movePlayer = () => {
if (keys['ArrowUp'] && player.y >= player.speed) {
player.y -= player.speed;
player.frameY = 3;
player.moving = true;
}
if (
keys['ArrowDown'] &&
player.y + player.height <= canvas.height - player.speed
) {
player.y += player.speed;
player.frameY = 0;
player.moving = true;
}
if (keys['ArrowLeft'] && player.x >= player.speed) {
player.x -= player.speed;
player.frameY = 1;
player.moving = true;
}
if (
keys['ArrowRight'] &&
player.x + player.width <= canvas.width - player.speed
) {
player.x += player.speed;
player.frameY = 2;
player.moving = true;
}
};
const changeSpriteFrame = () => {
if (player.frameX < 3 && player.moving) {
player.frameX++;
} else {
player.frameX = 0;
}
};
window.addEventListener('keydown', event => {
keys[event.key] = true;
});
window.addEventListener('keyup', event => {
delete keys[event.key];
player.moving = false;
});
const animate = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawSprite(
playerSprite,
player.width * player.frameX,
player.height * player.frameY,
player.width,
player.height,
player.x,
player.y,
player.width * 2,
player.height * 2,
);
movePlayer();
changeSpriteFrame();
};
let fps, fpsInterval, startTime, now, then, elapsed;
const startAnimating = fps => {
fpsInterval = 1000 / fps;
then = Date.now();
startTime = then;
animationFrame();
};
const animationFrame = () => {
requestAnimationFrame(animationFrame);
now = Date.now();
elapsed = now - then;
if (elapsed > fpsInterval) {
then = now - (elapsed % fpsInterval);
animate();
}
};
startAnimating(10);