Home > Back-end >  Reversing a moving object in JS
Reversing a moving object in JS

Time:06-14

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!!

CodePudding user response:

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

CodePudding user response:

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.

  • Related