-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
72 lines (60 loc) · 2.32 KB
/
script.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
function change_steve(src) {
steve.src = src;
return true;
}
function move_steve(x = 0) {
let steve_pos = steve.getBoundingClientRect();
// If the steve is inside de nav move it, if it is in the border don't.
if (x > 0 && steve_pos.right < nav_pos.width + nav_pos.left)
steve.style.transform = `translateX(${steve_pos.left - initial_left_pos + x}px)`;
else if (x < 0 && steve_pos.left > nav_pos.left)
steve.style.transform = `scaleX(-1) translateX(${-(steve_pos.left - initial_left_pos + x)}px)`;
return true;
}
// After DOM has been loaded.
document.addEventListener("DOMContentLoaded", function() {
// Gets the nav positions.
let nav = document.getElementsByTagName("nav")[0];
nav_pos = nav.getBoundingClientRect();
// Gets the steve positions.
steve = document.getElementById("steve");
initial_left_pos = steve.getBoundingClientRect().left;
// Gets buttons positions.
a_btn = document.getElementById("a");
d_btn = document.getElementById("d");
let idx = 0;
document.addEventListener("keydown", function(event) {
if (idx > 5)
idx = 0;
// Change the image to the next one whenever you press w or a or s or d.
if (event.key == "d" || event.key == "a") {
steve.src = `images/steve/${idx}.png`
idx++;
}
// Moves the steve if you press w or a or s or d.
if (event.key == "a") {
move_steve(-6);
// The key will turn blueish and white text.
a_btn.style.color = "white";
a_btn.style.backgroundColor = "#197278";
}
else if (event.key =="d") {
move_steve(6);
// The key will turn blueish and white text.
d_btn.style.color = "white";
d_btn.style.backgroundColor = "#197278";
}
});
document.addEventListener("keyup", function(event) {
if (event.key == "a") {
// The key will return to normal.
a_btn.style.color = "";
a_btn.style.backgroundColor = "";
}
else if (event.key =="d") {
// The key will return to normal.
d_btn.style.color = "";
d_btn.style.backgroundColor = "";
}
});
});