How do I stop two NPCs from walking into each other and being unable to move?
I'm creating a 2D game, similar to the older generations of Pokemon or Final Fantasy. I have NPCs which walk following a grid-like pattern, using a script which was derived from the Unity 2D Roguelike tutorial. Basically, the NPCs use raycasts to check if a tile is occupied. If it isn't, they move onto it. Sometimes, though, an NPC and a different NPC both scan the same coordinate at the same time, and determine it's safe to move in, because it isn't inhabited. This leads to them both moving onto the tile, stopping them from escaping because their raycast checks always pick up the other NPC on that tile. The player can do this as well, and be in the same tile as an NPC. Are there any simple solutions to solve this?
void Update () {
//If the NPC isn't able to check if they can move, end the function
if (!canCheck || !ableMove) return;
//If the appropiate amount of time has been waited
if (intervals >= howOftenMoves)
{
//The NPC can no longer move again until the functions are over
ableMove = false;
//The raycast for the Move function
RaycastHit2D hit;
//Checks whether the moving process has worked
bool hasWorked = false;
//Array of directions has been mixed up
pd = mixer[pd];
//Counting up from each possible direction from the list
for(int i = 0; i < pd.Length; i++)
{
hasWorked = Move(pd[i].xDir, pd[i].yDir, out hit);
//If the movement with the directions has worked, set the animations and stop the rest of the code
if (hasWorked)
{
anim.SetBool("IsMoving", true);
anim.SetFloat("MoveX", pd[i].xDir);
anim.SetFloat("MoveY", pd[i].yDir);
intervals = 0;
return;
}
}
//Resets the blockingLayer so that player can get out, and player cannot interact with npc
gameObject.layer = 0;
ableMove = false;
intervals = 0;
//Makes the NPC appear dull
spr.material.color = new Color(0.6f, 0.6f, 0.6f);
//Makes the check to see if the player is still on the npc in 5 seconds
InvokeRepeating("TurnOnNpc", 5, 5f);
//for(int i = 1; i < 4)
}
//Else, if the NPC is able to move, add up the intervals
else intervals++;
}
(The whole "pd mixer stuff" is just an array of X/Y coordinates that are "mixed" to randomly generate a direction to move for NPCs, so they can move randomly. )
Your answer
Follow this Question
Related Questions
Issue with 2D raycast 0 Answers
Raycast2D getting errors 0 Answers
Line of sight for multiple targets - AI - in a 2d game 1 Answer
Raycasting Not Working 1 Answer