Hello community!
I’m currently scratching my head trying to figure out a tricky system to make an object move randomly using Waypoints, but ignoring waypoints behind walls. What I essentially need is the object to get a list of the weypoints, pick randomly one of them, and move towards it only if the waypoint is visible, otherwise it should scan again for another random waypoint from the list.
In the diagram above, the yellow object should randomly move in the light green directions only. Making the object get a list of the waypoints, randomly pick one of them and move towards it is easy and I’ve already managed to do it (I0m a noob at arrays, but tutorials helped me with that). What I can’t do is checking if the random waypoint is behind the wall and, if so, scan again for a visible waypoint.
It’s super convoluted, I know. I hope I’ve been able to make understand my goal. Looking forward any response!
Might want to start with some LOS (Line Of Sight) tutorials on Youtube… Depends if you are 3D or 2D which kind to try out, but they’ll have ways of determining what you want above.
As far as picking a random one, either shuffle if you don’t want double-choices, or pick random with Random.Range();
Yeah, I forgot to specify that my project is 3D.
I’m already using Random.Range to pick one of the waypoints from the array, which I set up in the inspector. What I don’t know how to do is checking if that waypoint is behind a wall, and if so rescan the array again for another random waypoint
var checkPos = Random.Range(0, MovingPositions.Length - 1);
for (int i = 0; i < checkPos; i++)
{
if (Physics.Linecast(transform.position, MovingPositions[checkPos].transform.position, 1 << 12)
{
randomPos = checkPos - 1;
}
}
In short, a Linecast checks through the loop until there’s an object of layer 12 (the wall) between the unit and the waypoint, and then sets the desired waypoint as the previous one. It’s okay-ish atm, but the downside is that the previous waypoint sometimes is in sight from a position but becomes unaccessible once the unit gets close (my game has also some verticality in mind), and the following waypoints are ignored even if they fit the requirements
Better would be to store all visible points (while looping through them) into another array, then randomly choose from that. So use for (int i = 0; i < MovingPositions.Length; i++)
to check all of them, and the true ones get put into the other array of visible possible targets.