Moving along odd angles

Ok currently I have a game piece object at position 1,1 and I move it to position 5,4. Its just a simple repaint from there to here.

But in my move() call I want to animate the piece sliding on the board. I already do simple move calls to float text or move a card in straight lines. But its always only on one axis, either x or y.

And the moving of a game piece can be at any odd angle. So what type of equation should I be looking to use to figure out my where to redraw the gamepiece as it slides along the board.

I current brain storm was something like this.


void setDestination(int destX, int destY) {
      this.destX = destX;
      this.destY = destY;
      
      if(currentX < destX){
            moveX = 1;
      }else{
            moveX = -1;
      }
      
      if(currentY < destY){
            moveY = 1;
      }else{
            moveY = -1;
      }
      
      moving = true;
}

void move() {      
      if(moving == false) return;
      
      if(currentX != destX)
            currentX += moveX;
      
      if(currentY != destY)
            currentY += moveY;
      
      if(currentX == destX && currentY == destY)
            moving = false;
}

Is there a better way to do this?

Actually thats pretty ugly. It moves at an angle depending on the x and y. Then it may move in a straight line to get to the bigger point.




\ _ _ _

So it works but is crap. So whats the proper way to do this?

I’m pretty new to trig so I apologize if I’m totally wrong (I didn’t test) :stuck_out_tongue:

first you need to find the angle between the two points. use this method:


protected double calcAngle(Point p1,Point p2) {
      return Math.atan2(p2.y-p1.y,p2.x-p1.x)*180.0/Math.PI;
}

note: it’s a better idea to use atan2 because atan cannot handle a full circle…

Then to move along at that angle, use:


piece.x+=Math.cos(angle)*velocity;
piece.y+=Math.sin(angle)*velocity;

where velocity is how fast you want it to move

Looks good, I’ll plug it in when I get home and try it out.