Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

210
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda