Skip to main content
3 of 3
Updated to answer updated question
Ray Dey
  • 6.9k
  • 3
  • 38
  • 45

You will want to look into vector maths for this. The basic way you would handle this is as follows:

You'd want two variables as your "heading", this will tell you the direction you want to be heading in.

Let's call them hX and hY.

hX = dX - oX
hY = dY - oY

You should probably normalize these values (meaning, the length of the vector is equal to 1). You do that by performing the following:

Length = sqrt( hX^2 + hY^2 )
hX = hX / Length
hY = hY / Length

Now you can use a speed multiplier to determine how quickly you want your agent to move to the destination position.

currentX += hX * SPEED
currentY += hY * SPEED

That should be everything really. To make this a LOT easier, it might be worth looking into incorporating a maths library with SDL so that you can use vectors and vector operations.

EDIT FOR UPDATED QUESTION:
The way you have your while loop at the moment will lock up your entire game until the player has arrived at the position.

A better way is to have a standard game loop with an Update() function like so:

public class Game
{
    // Other implementations left out
    public void Update()
    {
        UpdatePlayer()
    }
};

In your UpdatePlayer() function you can call MovePlayer() and within MovePlayer() since the Length variable is always updated every time you call the function, all you have to do is update MovePlayer() to do something like this:

private static void MovePlayer(double x2, double y2, int duration)
{
    double hX = x2 - m_PlayerPosition.X;
    double hY = y2 - m_PlayerPosition.Y;

    double Length = Math.Sqrt(Math.Pow(hX, 2) + Math.Pow(hY, 2));

    if( Length < 0.1f )    // Less-than rather than Length == 0.0 to handle floating point errors
        return;

    hX = hX / Length;
    hY = hY / Length;

    m_PlayerPosition.X += Convert.ToInt32(hX * 1);
    m_PlayerPosition.Y += Convert.ToInt32(hY * 1);

    UpdatePlayerLocation();
}
Ray Dey
  • 6.9k
  • 3
  • 38
  • 45