Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
Reversing a moving object in JS

My task is to create a ball and make it move back and forth across the screen. I have made it move in one direction but am having issues making it go in reverse. Here's what I have thus far:

function moveBall() {
  positionX = positionX + velocity;
  ball.style.left = positionX + 'px';
  let reserve = false
  if (positionX = 20000 + 'px') return;
  !reverse;
}

The if statement only stops the ball at a certain point but doesn't make it turn around.

I'm sure it's something really simple that I'm just overlooking, especially at this point because I've been googling the hell out of this, so if anyone can give a noobie a hand that would be much appreciated!!

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

Try this code, which uses a variable reverseNum to track whether or not the velocity should be negated.

HTML:

<body></body>

JS:

document.body.onload=function(){
ball=document.createElement("DIV");
ball.style.width="100px"; //Ball radius
ball.style.height="100px"; //Ball radius
ball.style.borderRadius="100%";
ball.style.backgroundColor="red";
ball.style.position="absolute";
document.body.appendChild(ball);
setInterval(function(){moveBall()},100)}
var positionX=0;
var velocity=100;
var reverseNum=1;//1 if should reverse is false, -1 if should reverse is true
function moveBall() {
  positionX = positionX + velocity*reverseNum;
  ball.style.left = positionX + 'px';
if(positionX>20000){
reverseNum=-1;
}
}
about 4 years ago · Santiago Gelvez Relatório

0

positionX = positionX + velocity;

So by adding velocity to positionX makes it go forth, then reverse of it, which is minus velocity will make it come back.

And use if condition to separate the forth and back.

for eg.

function moveBall() {
  if (positionX = 20000 + 'px'){
    positionX -= velocity; //same as positionX = positionX - velocity;
  }else{
    positionX += velocity;
  ball.style.left = positionX + 'px';
  let reserve = false; // not sure what you trying to do with this;
  !reverse;  // and this
}

and if you want to get current moving status by the reverse , just set false when minus and true and plus.

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda