Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
Invertir un objeto en movimiento en JS

Mi tarea es crear una bola y hacer que se mueva de un lado a otro de la pantalla. Hice que se moviera en una dirección, pero tengo problemas para que vaya en reversa. Esto es lo que tengo hasta ahora:

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

La instrucción if solo detiene la pelota en un punto determinado, pero no la hace girar.

Estoy seguro de que es algo realmente simple que simplemente estoy pasando por alto, especialmente en este punto porque he estado buscando en Google, ¡así que si alguien puede echarle una mano a un novato, sería muy apreciado!

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

Pruebe este código, que usa una variable reverseNum para rastrear si la velocidad debe ser negada o no.

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 Report

0

positionX = positionX + velocity;

Entonces, al agregar velocidad a la posición X, hace que avance, luego, al revés, que es menos velocidad, hará que regrese.

Y use la condición if para separar la ida y la vuelta.

por ej.

 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 }

y si desea obtener el estado de movimiento actual al reverse , simplemente configure falso cuando menos y verdadero y más.

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!