Say your 20 feet in front of me in the x direction, and 10 feet higher than me in the y direction. To get to you, I need to move 20 feet forward, and 10 feet up.
So think of a right triangle with sides 20, 10, and hypotenuse. The hypotenuse will be of length sqrt(20 * 20 + 10 * 10). This is the distance between us.
In physics you often want to "normalize" so that your triangle has a hypotenuse of 1. So, you need to divide everything by the length of the hypotenuse.
Now you can move 10 / sqrt(20 * 20 + 10 * 10) in the y direction, and 20 / sqrt(20 * 20 + 10 * 10) in the x direction, and you will be 1 foot closer along a linear path between us. We call this pair of normalized value a unit vector, or normalized direction vector.
I'll abbreviate unit_vector_x as uv_x, and the distance in x direction just xd ...
1 2 3 4 5 6 7 8 9
|
double xd = monster_x - pos_x;
double yd = monster_y - pos_y;
double d = sqrt(xd * xd + yd * yd);
double uv_x = uv_x / d;
double uv_y = uv_y / d;
double speed = the speed you want it to move at.
|
Of course speed is distance over time.
We call the elapsed time delta time, and the change in position delta x or delta y.
1 2 3 4 5
|
double delta_x = uv_x * speed * delta_t;
double delta_y = uv_y * speed * delta_t;
pos_x = pos_x + delta_x;
pos_y = pos_y + delta_y;
|