CSS:
.dragon {
background-image: url(images/dragon.png);
background-position: center;
background-size: contain;
background-repeat: no-repeat;
width: 180px;
height: 120px;
position: absolute;
bottom: 0;
left: 2000px;
animation: ani-dragon 6s linear infinite;
}
@keyframes ani-dragon {
0% {
left: 2000px;
}
100% {
left: -500px;
}
}
.ani-dino {
animation: ani-dino 1s linear;
}
@keyframes ani-dino {
0% {
bottom: 0;
}
50% {
bottom: 300px;
}
100% {
bottom: 0;
}
}
Javascript
let dino = document.querySelector(".dino");
let dragonAnimationTime = parseInt(window.getComputedStyle(dragon).getPropertyValue("animation-duration"));
let dragonPosition = window.getComputedStyle(dragon);
let newAni = 6;
document.addEventListener("keydown", function (e) {
if (e.key == "ArrowUp") {
dino.classList.add("ani-dino");
setInterval(() => {
if (newAni > 2 && Math.round(parseInt(dragonPosition.left)) < -490) {
newAni = dragonAnimationTime - 0.1;
dragon.style.animationDuration = newAni + "s";
dragon.style.left = "2000px";
dragonAnimationTime = newAni;
}
}, 1);
setTimeout(() => {
dino.classList.remove("ani-dino");
}, "1000");
}
});
The problem is with the animation the dragon which is suppose to animate from right to left, is not working fine. As i am decreasing the animation time everytime the 'ArrowUp' is triggered and dragon successfully pass it and goes to extreme left. Animation duration is decreasing as expected and dragon animation is getting fast as it should be, but the problem comes that the dragon animation sometimes start randomly from anywhere as it should start everytime from extreme right as per my code, but in between it startes sometimes randomly while playing, from anywhere of its path, i really cant understand why it is so.
I tried whatever i can , I tried to change the durations, i tried to change length of the horizontal path of dragon, i tried both setInterval and setTimeout with different codes and logics.
But really cant understand why the animation sometimes begins from in between the path, although i am everytime putting it to the extreme right once it met conditions of decreasing the animation-duration and also i am decreasing the animation-duration at the extreme right of it(-490px), so that the current running path is not effected, still not working.
Please help if someone got this !!!