JAVASCRIPT JOURNEY : DAY 19
CHAPTER 19 : A PLATFORM GAME
Platform games (or “jump and run” games) expects the player to move a figure through a world.
CODE is plain JavaScript , can run directly in any web browser.
First we have index.html file:
<!DOCTYPE html>
<html lang="en" onclick="jump()">
<head>
<meta charset="UTF-8">
<title>Jump Game</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="game">
<div id="character"></div>
<div id="block"></div>
</div>
<p>Score: <span id="scoreSpan"></span></p>
</body>
<script src="script.js"></script>
</html>
Here we have three divs =3 heros: game , character and block
STYLE.CSS:
padding: 0;
margin: 0;
overflow-x: hidden;
}
.game{
width: 500px;
height: 200px;
border: 1px solid black;
margin: auto;
}
#character{
width: 20px;
height: 50px;
background-color: red;
position:relative;
top: 150px;
}
.animate{
animation: jump 0.3s linear;
}
@keyframes jump{
0%{top: 150px;}
30%{top: 100px;}
70%{top: 100px;}
100%{top: 150px;}
}
#block{
background-color: blue;
width: 20px;
height: 20px;
position: relative;
top: 130px;
left: 500px;
animation: block 1s infinite linear;
}
@keyframes block{
0%{left: 500px}
100%{left: -20px}
}
p{
text-align: center;
}
Here we tried to style div's to their appropriate width and height and then added animation to character to jump and to block to slide towards character.
```var character = document.getElementById("character"); var block = document.getElementById("block"); var counter=0; function jump(){ if(character.classList == "animate"){return} character.classList.add("animate"); setTimeout(function(){ character.classList.remove("animate"); },300); }
Here we first tried to grab character and block . Then added an onlclick to html for jumping function of character.
Now the function jump() will add / remove class animate(to make character jump) in 500ms repeatedly as we click.
![js.PNG](https://cdn.hashnode.com/res/hashnode/image/upload/v1608110987569/zdd6phUtG.png)
Any and every time we spam jump , it adds on the class animate to it,
or try to add the class "animate" only if it is not added.
Now we need to add hit-detection onto the game if they are on top of each other.
```var checkDead = setInterval(function() {
let characterTop = parseInt(window.getComputedStyle(character).getPropertyValue("top"));
let blockLeft = parseInt(window.getComputedStyle(block).getPropertyValue("left"));
if(blockLeft<20 && blockLeft>-20 && characterTop>=130){
block.style.animation = "none";
alert("Game Over. score: "+Math.floor(counter/100));
counter=0;
block.style.animation = "block 1s infinite linear";
}else{
counter++;
document.getElementById("scoreSpan").innerHTML = Math.floor(counter/100);
}
}, 40);
So what you will do is :
Get the top position of character and left position of block.
Then compare them against each other , if they are inside of each other.
if hit , remove animation!!
This is the simple game.
Happy Learning:-)