Answer the question
In order to leave comments, you need to log in
How to loop animation in JavaScript?
Decided to make a Space Invaders game in JavaScript.
The essence of the question is this:
I wrote the code, but it does not work as we would like (the invaders block should move either to the left or to the right smoothly, but it blinks, disappears, and generally behaves inappropriately if you increase its speed or increase the frequency of the function call)
itself the code is here:
let timer;
let direction = 'left';
function moving() {
if(direction == 'left'){
let start = Date.now();
timer = setInterval(function() {
let timePassed = Date.now() - start;
invaders.style.marginLeft = timePassed / 4 + 'px';
if (invaders.style.marginLeft.slice(0,invaders.style.marginLeft.indexOf('p')-1) > 670) {clearInterval(timer); direction = 'right'};
}, 20);
}
else{
start = Date.now();
timer = setInterval(function() {
let timePassed = Date.now() - start;
invaders.style.marginLeft = (685 - timePassed / 4) + 'px';
if (invaders.style.marginLeft.slice(0,invaders.style.marginLeft.indexOf('p')-1) < 10) {clearInterval(timer); direction = 'left'};
}, 20);
}
}
window.onload = setInterval(moving, 3000);
Answer the question
In order to leave comments, you need to log in
Wildly blunted, everything can be implemented much easier:
let direction = 'left';
let invaders = document.getElementById("invaders");
let i = 0;
function move() {
if(i > 677) {
direction = 'right'
}
else if (i < 5){
direction = 'left'
}
if(direction == 'left'){
invaders.style.left = i + 'px';
i++;
}
else if(direction == 'right'){
invaders.style.left = i + 'px';
i--;
}
}
window.onload = setInterval(move, 10)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question