Home » Java » java – How to make an object move in increments-Exceptionshub

java – How to make an object move in increments-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m stuck at how to write code to make an object move in increments to the desired amount and not just jump straight to the end goal.

e.g.

Move an object from 1 – 500 (x,y, coordinates [0,1] to [0,500]) by going 1, 2, 3, 4, 5……..
and not 1 to 500 in one movement?

      else if(direction == 'D'){
         xInc = 0;
         yInc = 1;
         this.setXPos(this.xPos +(distance * xInc));
         this.setYPos(this.yPos +(distance * yInc));
         this.alignAll();
         this.delay(20);
      }

   }  

Here is my full code I have so far any help would be greatly appreciated TIA.

How to&Answers:

you can add a loop between your assignment something like :

  if(direction == 'R'){
  xInc = 1;
  yInc = 0;
  for(int index= 0; index <= distance;index ++){
    this.setXPos(this.xPos +(xInc));
    this.setYPos(this.yPos +(yInc));
    this.alignAll();
    this.delay(20);  
  }

}

I also strongly recommend you to externalize this function, since it will be almost the same depending on your direction.