2d movement to a diagonal destination?

I’m trying to figure out how to get a 2d image or box to travel gradually from point A to point B. Point B’s Y coordinate being different from point A causing the travel to be diagonal.

// Simple example starting at XY coordinates 5,5
// Destination being XY coordinates 700,700

Rect myRect;
bool arrived = false;

myRect.x = 5; 
myRect.y = 5;
if(arrived == false)
  // HELP!
  // Dont know the math equation that would go here to increase x y coordinates 
  // to gradually travel to 700,700

  // Check if myRect has arrived to destination 700,700
  if(myRect.x >= 700 && myRect.y >= 700)
    // Has arrived so end the check condition
    arrived = true;
    // Set the coordinates to 700,700 in case calculation went slightly over 700,700
    myRect.x = 700;
    myRect.y = 700;


Use Lerp, such as in MoveObject.

If i stop myRect.y once it reaches 200 and allow X to keep moving until it reaches 500 its no longer a smooth diagonal transition. Some kind of calculation is missing in the code for diagonals.

umm of course that happens your removing the Vertical velocity for the diagonal. you need to make a slope for the rect to climb, you can do this by using the Year 10 Linear calculation.


heres the math:

you want y = 200 when x is 500
it starts at 0,0

= 0.4f

therefore through cross multiplying we get
2x = 5y

so we have our equation to use now we apply to a speed.
    speedx = 10f  //(2 * 5)
    speedy = 25f //(5 * 5)

using this it can get you from ANY point to ANY other point diagonally (provided they don’t have any matching coord axis and the numbers are realistic) you can use this to solve your problem. you can even do it to make an array of paths for witch an object gets to certain of coordinates. for curved lines many options are possible including polynomials which is a little more advanced.

hope it helps :slight_smile: