Question

I have a grid like this one

And I need to calculate the distance from a cell respect a target. For example cell 64 is the target and cell 99 is the current position.

A possible path for 99 must be for example cell 83, 83, 66 and 65 The path 76, 62, 63 is not correct.

I calculate the distance with this function but I think that is not well weighted

-(float)distanceFromTarget:(int)targetCoordinate ofCurrentObject:(int)objectCoordinate{


    int columnTarget = (targetCoordinate % 15)-1;
    int lineTarget = (targetCoordinate /15);

    int columnObject = (objectCoordinate % 15)-1;
    int lineObject = (objectCoordinate /15);

    float lato1;
    float lato2;

    if(columnObject>columnTarget) {
        lato1 = columnObject - columnTarget;
    }
    else lato1= columnTarget - columnObject;

    if(lineObject>lineTarget) {
        lato2 = lineObject - lineTarget;
    }
    else lato2= lineTarget - lineObject;


    float distance = sqrt(pow(lato1,2)+pow(lato2,2));

    return distance;



}
Was it helpful?

Solution

First of all, your calculation of the column and line index is not correct (it gives a wrong result for the last cell in each row). If the grid has 15 columns and the first cell has #1 then it should be:

int columnTarget = (targetCoordinate - 1) % 15;
int lineTarget = (targetCoordinate - 1) / 15;

int columnObject = (objectCoordinate - 1) % 15;
int lineObject = (objectCoordinate - 1) / 15;

Then you can compute the horizontal and vertical difference as

int deltaX = abs(columnObject - columnTarget);
int deltaY = abs(lineObject - lineTarget);

But the final step depends on what kind of distance you want to compute.

float distance = sqrt(pow(deltaX,2)+pow(deltaY,2));
// Or better:
float distance = hypotf(deltaX, deltaY);

gives the "Euclidean distance", i.e. the length of a straight line between the centers of the cells.

If you want to calculate the "shortest path" where horizontal, vertical and diagonal moves are allowed then the distance would be

int distance = MAX(deltaX, deltaY);

If only horizontal and vertical moves are allowed then the length of the shortest path is

int distance = deltaX + deltaY;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top