forked from petyoMitkov/Canvas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path09. SoftUni_Mario Jump.html
86 lines (77 loc) · 2.3 KB
/
09. SoftUni_Mario Jump.html
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
<!DOCTYPE html>
<html>
<head>
<title>Mario Jump</title>
</head>
<body>
<canvas id="canvas" width="800" height="500" style="border: 2px solid green"></canvas>
<script type="text/javascript">
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
let marioImg = new Image();
marioImg.src = "SuperMario.jpg";
let marioObj = {
"x": 50,
"y": 200,
"constantFloor": 250,
"onGround": true,
"onTop": false,
"jumpStart": false,
"jumpCounter": 0
}
let keysObj = {};
window.addEventListener("keydown", keyHandler);
window.addEventListener("keyup", keyHandler);
function draw() {
ctx.beginPath();
ctx.fillStyle = "white";
ctx.fillRect(0,0,800,500);
ctx.drawImage(marioImg,marioObj.x,marioObj.y);
}
function keyHandler(event) {
if (event.type == "keydown") {
keysObj[event.code] = true;
} else if (event.type == "keyup") {
delete keysObj[event.code];
}
}
function updateControls() {
if (keysObj["ArrowRight"]) {
marioObj.x += 5;
}
if (keysObj["ArrowLeft"]) {
marioObj.x -= 5;
}
if (keysObj["Space"]) {
if (marioObj.y == marioObj.constantFloor ) {
marioObj.jumpStart = true;
}
if (marioObj.y < marioObj.constantFloor ) {
marioObj.onGround = false;
}
}
}
function marioPhysics() {
if (marioObj.jumpStart == true && keysObj["Space"] == true) { //jump
marioObj.y -= 15;
if (marioObj.y <= 30) {
marioObj.jumpStart = false;
}
} else if (marioObj.onGround == false && marioObj.y < 200) { //falling
marioObj.y += 10;
} else if (marioObj.y >=200) { // set mario on floor when falling
marioObj.y = marioObj.constantFloor;
marioObj.onGround = true;
}
}
function mainGameLoop() {
draw();
updateControls();
marioPhysics();
requestAnimationFrame(mainGameLoop);
}
mainGameLoop();
//setInterval(mainGameLoop, 10);
</script>
</body>
</html>