As I venture into the world of JavaScript as a beginner, I'm working on creating a simple game. In this game, there are pieces of 'rubbish' (represented by divs) floating from right to left down a river. The goal is for the player to click on the div and make it disappear.
However, I've hit a roadblock in adding randomness to the animation. I want each piece of rubbish to take a different path instead of following a fixed trajectory.
I had an idea to introduce a random value into the 'top' percentages of the keyframe animation. Here's a snippet of what I have so far - any suggestions on how to improve it? I wouldn't mind shifting all the animation logic into JS.
const btnRubbish = document.querySelector('div.smallrubbish')
const x = (Math.random() * 100)
btnRubbish.style.transform =
`@keyframes rubbish {
0% {top: ${x}%; left: 100%;}
50% {top: ${x}%; left: 50%;}
100% {top: ${x}%; left: 0%;}
`
HTML
<div class="game box">
<div class="smallrubbish"></div>
</div>
Relevant CSS
div.smallrubbish {
display: block;
height: 50px;
width: 50px;
background-color: rgba(255, 124, 0, 1);
border-radius: 100%;
position: absolute;
top: 50%;
left: 100%;
animation-name: rubbishflow;
animation-duration: 8s;
animation-timing-function: linear;
animation-iteration-count: 1;
animation-delay: 0s;
animation-fill-mode: forwards;
}
@keyframes rubbishflow {
0% {top: 50%; left: 100%;}
50% {top: 25%; left: 50%;}
100% {top: 60%; left: 0%;}
}