Trying to incorporate gravity into a circular object in an HTML, CSS, and JavaScript game. Here is the relevant JavaScript code section:
Check out the code on repl.it: https://repl.it/join/wukcvzow-iamapersonthing
The specific part of interest in this tutorial is at the 06.44-minute mark:
Reference video tutorial at: https://youtu.be/3SsYZDJdeXk
JavaScript:
var block = document.getElementById("block");
var hole = document.getElementById("hole");
//add this for the setInterval function
var character=document.getElementById("character");
hole.addEventListener('animationiteration',() => {
var random = Math.random()*3;
var top = (random*100)+150;
hole.style.top=-(top) + "px";
});
//interval function runs every 10 milliseconds
setInterval(function(){
var characterTop =
//this is the gravity function
parseInt(window.getComputedStyle(character).getPropertyValue("top"));
character.style.top=(characterTop+3)+"px";
},10);
It seems like the issue might be related to this last segment:
},10);
Since the code doesn't show any syntax or other errors, it's challenging to troubleshoot further. I've also experimented with the CSS but couldn't pinpoint the root cause of the problem.
As per the tutorial, the "10" was suggested to be the refresh rate, but it doesn't seem to be the case. That number somehow affects the speed of the ball's downward movement. My goal is to have the entire animation (ball moving down) refresh every 10 seconds.
In summary, I want the pink ball (character element) to continuously descend every 10 seconds. Currently, it drops once and then falls off the screen. It only drops again when the "RUN" button is pressed.
The HTML code for this project:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>FlappyBird</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="sky">
<div class="ground">
<div id="game">
<div id="block"></div>
<div id="hole"></div>
<div id="character">
</div>
</div>
<script src="script.js"></script>
</body>
</html>
And the CSS styles:
*{
padding:0;
margin:0;
}
#game{
width:400px;
height:500px;
border: 1px solid greenyellow;
margin:auto;
overflow:hidden;
}
#character{
width:50px;
height:50px;
background-color:rgb(255, 0, 149);
position: absolute;
top:250px;
border-radius:50%;
}
#block{
width:50px;
height:500px;
background-color:greenyellow;
position: relative;
left:400px;
animation:block 2s infinite linear;
}
@keyframes block{
0%{left:400px}
100%{left:-50px}
}
#hole{
width:50px;
height:150px;
background-color:white;
position: relative;
left:400px;
top:-500px;
animation:block 2s infinite linear;
}
/*
.sky{
background-color:aqua;
width:400px;
height:500px;
position: relative;
}
.ground{
background-color:brown;
width:400px;
height:100px;
position: relative;
top:500px;
}
*/