C
C
cheIowek2020-11-13 10:08:05
css
cheIowek, 2020-11-13 10:08:05

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);

I had this idea: to create a function that moves either left or right, depending on the variable (in the future it will all be a method and object properties), the function is called cyclically (or the function itself is infinite) when it is necessary to change direction (width the block inside which the movement will be equal to 670-680, i.e. do not go beyond this framework)
I'm not sure that I'm thinking in the right direction, that's why I created this question here, if you have better ideas or ideas to improve the existing code - write them here, please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
cheIowek, 2020-11-13
@cheIowek

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 question

Ask a Question

731 491 924 answers to any question