8

I'm currently trying to create a video game where characters are AI and are in a circular map with ressources on it.

I'm currently trying to calculate the shortest distance betwing 2 points on this map but my problem is that the map is circular : for example

if my map is 20*20 and i m in (0,0) the (19,0) point has a distance on 1 only. I've been looking on the internet but i didn't found answers for my problem. I have to take care of the orientation (North South west East) of my character too, in he has to turn to go to the point, the distance has to be longer.

Is there an existing formula ?

Thanks for reading !

Loadex
  • 1,502
  • 1
  • 12
  • 25

2 Answers2

5

For every coordinate choose the minimal distance, and then use it as usual.

int dx = min(abs(x0-x1),20-abs(x0-x1));
int dy = min(abs(y0-y1),20-abs(y0-y1));

For euclid distance :

double dist = sqrt(dx * dx + dy * dy);

For Manhattan distance:

int dist = dx + dy;
RiaD
  • 46,822
  • 11
  • 79
  • 123
3

The problem remains a shortest path problem in a graph, you just need to add edges for the circular map:

G = (V,E) where V = {all squares} and E = { (u,v) | [(u.x + 1 % 20 = v.x or u.x -1 % 20 = v.x) and u.y == v.y] or ... [same for y] }

What the mathematical notation above says: there is an edge between two squares if (and only if), the difference between their x or y cordinates is 1 or -1 in Z20 (modolus 20 ring). Since the ring Z20 is circular itself - it solves the circularity problem of the map.

Given this graph you can use BFS to find the shortest path from a single source (no need for dijkstra's algorithm because the graph is unweighted)

Note: If there are not obstacles, just calculate it using your regular distance function, but use the Z20 ring instead of the Z field in your math.

amit
  • 175,853
  • 27
  • 231
  • 333
  • Thanks for your answer ! i will try this and i will come back if i have any problems ! – Loadex Jul 08 '12 at 09:52
  • @Loadex: I assumed there are obstacles in the path, this is why I recommended BFS, if it is not the case - you need to just calculate it as euclidean distance in the Z20 (modolus 20) field. – amit Jul 08 '12 at 09:53
  • No, there is no obstacle, but i have to calculate using orientation (cause every action in the game has a cost) and if i have to turn myself, it cost me one action ! – Loadex Jul 08 '12 at 09:56
  • 2
    Just a note: Z and Z_20 aren't fields. They are just rings. There are multiplicative inverses for every element in fields – RiaD Jul 08 '12 at 10:04
  • @RiaD: Thanks for the correction, I fixed it to be more accurate. – amit Jul 08 '12 at 10:06