如果球连续朝一个方向运动,如何反转球的方向?

How do you reverse the direction of a ball if continuously going in one direction?

var velocity = 100;
var positionX = 0;
var ball = document.getElementById('ball');

function moveBall() {
  var Xmin = 0;
  var Xmax = 300;
  
  positionX = positionX + velocity;
  ball.style.left = positionX + 'px';
}

setInterval(moveBall, 100);
img {
  position: absolute;
}
<img id="ball" width="150" height="150" src="https://tr.seaicons.com/wp-content/uploads/2016/11/Volleyball-Ball-icon.png"/>

我已经声明了我的全局变量,然后是移动球的函数,然后是 setInterval。但是,我似乎无法想出正确的方法来反转不断向屏幕右侧移动直到不再可见的球。是一种逆向方法还是设置条件的问题?

在下面的解决方案中,velocity变量用于改变移动速度。 updateDirection()方法用于通过检查positionX值来更改新的方向信息。

var ball = document.getElementById('ball');

/* This variable is used to change the movement speed. */
const velocity = 50;
/* This variable is used to change the amount of movement per unit time. */
const step = 10;
/* This variable stores the current or target position of the <img> element. */
var positionX = 0;
/* This variable stores the minimum position value. */
const xMin = 0;
/* This variable stores the maximum  position value. */
const xMax = 300;
/* true: right move, false: left move */
var direction = true; 

/* This method is used to change the direction of movement. */
function updateDirection() {
  if(positionX == xMax)
    direction = false;
  else if(positionX == xMin)
    direction = true;
}

function moveBall() {
  updateDirection();
  
  if(direction)
    positionX += step;
  else
    positionX -= step;
    
  ball.style.left = `${positionX}px`;
  
  console.clear();
  console.log(`Direction: ${direction ? "right" : "left"} Position: ${positionX} `);
}

/* Update the velocity value to change the movement speed. */
setInterval(moveBall, velocity);
img {
  position: absolute;
}
<img id="ball" width="150" height="150" src="https://tr.seaicons.com/wp-content/uploads/2016/11/Volleyball-Ball-icon.png"/>