Ricky
Ricky

Reputation: 883

How do I move one point towards another point in C++?

Say I have two points on an infinite 2D grid system.

The first point being a user controlled point at the X, Y coordinate set of (3,5).

The second point being a computer generated point at the X, Y coordinate set of (-20, 30).

I want the second point to move 5 units towards the first point every second. I already have the second point moving every 1 second, just not towards the first point.

I need to know how to move the second point towards the first point, and not in a random direction as it is now....

This is for a game by the way, where point 2 is a monster chasing point 1 (the player). It's being coded in C++.

Upvotes: 0

Views: 4521

Answers (1)

Michael Tontchev
Michael Tontchev

Reputation: 1139

Let's walk through it step by step.

Point 1 starts at (x,y). Point 2 is at (x2, y2).

The slope between them is m = (y2-y)/(x2-x). What does this tell us? It tells us that if we want to move from point 2 to point 1, for every 1 unit we move in the x direction, we need to go m in the y direction.

So now we already have an algorithm that will move them toward each other! Just not at the right speed.

How do we figure out how much in the x direction we should move point 2 so that after also moving in the y direction the correct amount, it will have moved 5 units total diagonally?

Well, if we move 1 unit in the x and m units in the y, we will have covered a distance of d = sqrt(1^2 + m^2) (Pythagorean theorem)

We want to travel some number X in the x direction, so that after traveling Xm in the y direction, we will have moved 5 units. Simple: the distance we move is d = sqrt(X^2 + (Xm)^2). Simply set d to 5:

5 = sqrt(X^2 + (Xm)^2)
25 = X^2 + (Xm)^2 = (m^2 + 1)*X^2
X^2 = 25/(m^2 + 1)
X = sqrt(25/(m^2 + 1))

Now, we already know what m is. So we just plug in and solve for X. But notice X will always be positive. This is because we squared an equation. Hence, you will have to figure out the right sign for X. (just check whether point 1 is to the left or right of point 2)

After we have that, we will know that point 2 has to move X units either left or right, and mX up or down.

Upvotes: 5

Related Questions