- Home /
Issues with Navmesh Pathfinding and casting a Ray on a transform position
Hello, I'm having issues with my NavMeshAgent pathfinding. So far I have a simple setup in which you can click anywhere on the "Ground" layer in my game and the Player will find a path there. However, I ran into a problem when I found that if you clicked on a "Non-Walkable" baked area, the player wouldn't move at all. I was hoping to solve this by making the player find the closest walkable point near the Obstacle " and then re-order the player to move to that new point. I saw some suggestions about using SamplePositions and FindClosestEdge but I didn't quite understand how they worked so I figured I'd try something a little simpler.
About the code: spawnPoint is a gameObject that I use for positioning things. Basically, I position spawnPoint on the center of the Obstacle that's blocking our Player's movement, then I make the spawnPoint face our Player, and finally I move the spawnPoint forward towards the Player with a loop, moving it Forward by very small increments while detecting if it's hitting any Obstacles via raycast. Once the raycast for Obstacles fails, that means that the spawnPoint isn't hitting an Obstacle so we can then tell our Player to move to the position of the spawnPoint.
This almost works, but I can't seem to get the spawnPoint to move towards the player properly. Also, is there a way to cast a Raycast without having to cast it Forward from the spawnPoint. I just want to detect if the spawnPoint is hitting an Obstacle, whether it be via Tag or Layer it doesn't matter. So how would I Raycast the transform.position of spawnPoint starting from the Camera so it's casting down towards the ground instead of Forward. Also, if anyone knows a better way of going about this that'd be great. Thanks for reading.
if (Input.GetMouseButtonDown(0))
{
Ray castPoint = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(castPoint, out hit, Mathf.Infinity, obstacleLayer))
{
var hitPoint = new Vector3(hit.point.x, hit.point.y, hit.point.z);
spawnPoint.transform.position = hitPoint;
spawnPoint.LookAt(playerAgent.transform.position);
for (int i = 1; i < 100; i++)
{
spawnPoint.localPosition += spawnPoint.forward * 0.20f;
RaycastHit hitObs;
if (Physics.Raycast(spawnPoint.transform.position, spawnPoint.transform.forward, out hitObs, obstacleLayer))
{
Debug.Log("Hit an Obstacle");
}
else
{
Debug.Log("Found a new Point");
point = new Vector3(spawnPoint.position.x, playerAgent.transform.position.y, spawnPoint.position.z);
playerAgent.SetDestination(point);
isNavMoving = true;
playerAgent.transform.LookAt(point);
break;
}
}
}
}