1

How do I calculate the amount of "steps" there is from one field to another in a grid, moving orthogonally?

I am implementing an A* pathfinding system for a game that I am developing, and this simple mathematical operation is in my way.

I should probably re-attend third grade. Haha.

Mathias Lykkegaard Lorenzen
  • 15,031
  • 23
  • 100
  • 187

2 Answers2

3

If I understand correctly, I think you just add up the x,y movements necessary. Given two points (x1,y1) and (x2,y2), then the distance (assuming "moving orthogonally" means moving only horizontally and/or vertically) then it is:

abs(x1-x2) + abs(y1-y2)

For example, moving from position (1,1) to (3,4) means moving 2 spaces to the right and 3 spaces up for a total of 5. abs(1-3)+abs(1-4) = 2 + 3 = 5

Mark Wilkins
  • 40,729
  • 5
  • 57
  • 110
  • Are you sure that this answer is correct? In Direct X class we were taught to find the distance between two grid points using the Pythagorean theorem. Although your answer may be a different approach, I would expect to find the same outcome using both solutions. And when I punch your numbers in (1,1) (3,4) I get an out come of 4.4721 , not 5. – clamchoda Mar 30 '11 at 19:53
  • @Chris: Based on my understanding of the OP, it is correct. He stated that the moves were orthogonal (at right angles). To move from position (0,0) to (1,1) it means the move has to be either (0,0)->(0,1)->(1,1) or (0,0)->(1,0)->(1,1). That is a movement of two cells. You are correct that a straight line on graph paper in that case is a distance of sqrt(2). But as I understand the OP, the moves are not in a straight line. – Mark Wilkins Mar 30 '11 at 20:01
  • Ahh thank you Mark! My mistake Mark. I did not notice A* when I first read, I just read "A pathfinding system", guess I should be more careful! Thank you very much for taking the time to clarify. – clamchoda Mar 30 '11 at 20:07
0

I do believe this is a matter of simple math.

Surely, you know your starting x / y values, and your ending x / y values. To get the distance between the two, you do this:

dist = sqrt(dx^2 + dy^2 )

Where dx is the difference between the x-coordinates of the points Where dy is the difference between y-coordinates of the points.

So, for example. Lets say co-ordinate A is A(15,20) and co-ordinate B is B(35,5);

dx = 35 - 15 = 20; dy = 20-5 = 15;

Therefore;

dist between AB = sqrt(20^2 + 15^2) = 25.0 units.

Now for your final answer, this depends how many units a "step" is in your program. If a step is 5 units, (25/5) than there is 5 steps needed to get from point A to B.

clamchoda
  • 4,411
  • 2
  • 36
  • 74