# How to convert world coordinates to grid movement

I'm producing a tactical 3D RPG game and I have the following issue:

I want the NPC to move through the grid. The grid is formed by tiles and each tile has a script attached to it. In this script, there is a variable called TilePosition which is a Vector2Int, that I use it to stores its X and Y values in the grid. The NPC character has a script attached to it called NPCPlayer, where a use a Vectir2Int named NPCGridPosition to stores its position in the grid.

Also regarding the NPC, he has a script called NPCMovement. In this script, I've set a raycast that starts from the NPC feet and goes down. I use the raycast to take the TilePosition variable as it is written in the code:

public void MoveNPC()
{
if (Physics.Raycast(transform.position, Vector3.down * MaxDistance, out hitDown))
{
if(hitDown.transform.tag == "Tile")
{
Tile TilesPosition = hitDown.transform.gameObject.GetComponent<Tile>();
NPCPlayer NPCPosition = this.GetComponent<NPCPlayer>();
}
}
}


However, when I try to move the NPC through the grid, 3 rows ahead, he goes away, because he moves according to the world position, rather than moving according to his tile position.

I'm using these lines of code to make him move:

public void MoveNPC()
{
if (Physics.Raycast(transform.position, Vector3.down * MaxDistance, out hitDown))
{
if(hitDown.transform.tag == "Tile")
{
Tile TilesPosition = hitDown.transform.gameObject.GetComponent<Tile>();
NPCPlayer NPCPosition = this.GetComponent<NPCPlayer>();

targetPosition.x = TilesPosition.TilePosition.x + 3 ;
targetPosition.y = TilesPosition.TilePosition.y;

this.transform.position = Vector3.MoveTowards(this.transform.position, targetPosition,velocity);
}
}
}


How could I make the NPC to move according to its position in the grid?

I'll be glad if someone can help me a little bit with this.

• Have you considered making this easy on yourself, by arranging your tile objects so the tile at (0, 0) in tile space is at (0, 0, 0) in world space, (1, 0) is at (1, 0, 0), (0, 1) is at (0, 0, 1), etc? Then you don't need to store a separate tile position variable at all, or query it via a raycast, it's just a matter of rounding. Commented Apr 17, 2020 at 12:18
• @DMGregory Yes I have, the tile at (0,0) is at (1,0,0) in world space. However I'll put in (0,0,0) and see how it goes. I think in this way, it'll be easier.Thanks for the advice. Commented Apr 17, 2020 at 13:44