- Home /
NPC Movement in a Tactical RPG Game
Hi friends,
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>();
Vector3 targetPosition;
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.