Search code examples
c#algorithmpath-findinga-star

How can I find the euclidean "zone" that a point on a 2D graph falls on?


I'm trying to speed up my A* implementation (really bad lag just at 10x10 grid!) and the worst performance hit is likely coming from this function:

public Vector2 CoordsToIndex(Vector2 coords)
{
    for (int i = 0; i < mapCols; ++i)
    {
            for (int j = 0; j < mapRows; ++j)
            {
                if (coords.X >= i * map[0, 0].length &&
                    coords.X < i * map[0, 0].length + map[0, 0].length)
                {
                    indexi = i;
                }
                if (coords.Y >= j * map[0, 0].height &&
                    coords.Y < j * map[0, 0].height + map[0, 0].height)
                {
                    indexj = j;
                }
            }
    }
return new Vector2(indexi, indexj);
}

My original implementation of it isn't quite right, but if I can get this working instead it will speed things up a lot (I use this function constantly):

// The below math isn't quite right
indexi = (int)((coords.X - (map[0, 0].length / 2)) / map[0, 0].length) - 1;
indexj = (int)((coords.Y - (map[0, 0].height / 2)) / map[0, 0].height) - 1;

if (indexi < 0)
{
    indexi = 0;
}

if (indexj < 0)
{
    indexj = 0;
}

map[0, 0].length is the length of the tile, and map[0, 0].height is the height of the tile. All tiles are uniform.

It has to be possible to come up with a formula to calculate this but I'm not really certain as to what it would be. Any pointers/help/answers would be appreciated!

EDIT: Er...actually I think the problem might be subtracting the length or height divided by two. That's fine for tile nodes since I store their position as the center of the tile, but for this it would give the wrong tile back...maybe that's the problem...checking.

EDIT: Ah..it's that AND remove the -1. Man I get so confused, funny how I spent about two hours last night totally confused by this and then seconds after finally posting for help the answer comes to me in a flash.

SOLUTION:

public Vector2 CoordsToIndex(Vector2 coords)
{
    int indexi = (int)(coords.X / map[0, 0].length);
    int indexj = (int)(coords.Y / map[0, 0].height);

    return new Vector2(indexi, indexj);
}

That looks so much better.


Solution

  • Well, the short and simple answer:

    indexi = (int)(coords.X/map[0,0].length)
    indexj = (int)(coords.Y/map[0,0].height)
    

    EDIT: Of course, OP edits post with almost this answer before I post this. /facepalm