Why is my raycasting only working once.
I'm raycasting in a predefined path from navmesh calculate path in a grid. The problem is it only hits one object down the path then it stops hitting things even though they are there so I then get stuck in an infinite loop. Any idea's on why it's only hitting one thing? Then stopping? I need to get a list of every game object in the path. Here's the code.
public float GetPathCost(NavMeshPath path, List<Tile> tempTiles)
{
float cost = 0f;
List<Tile> tilePath = new List<Tile>();
Vector3 destPos = path.corners[path.corners.Length-1];
Vector3 currentPos = path.corners[0];
currentPos.y -= 0.1f;
int j = 0;
while(!AtPosition(destPos, currentPos))
{
if (AtPosition(currentPos,path.corners[j]))
{
j++;
currentPos.y -= 0.1f;
}
Vector3 dir = (path.corners[j] - currentPos).normalized;
RaycastHit hit;
if (Physics.Raycast(currentPos, dir, out hit, 1))
{
Tile tempTile = hit.collider.GetComponent<Tile>();
if (tempTile)
{
tilePath.Add(tempTile);
currentPos = tempTile.transform.position;
}
}
}
for (int i = 0; i < tilePath.Count; i++)
{
int area = tilePath[i].GetComponent<NavMeshModifier>().area;
cost += NavMesh.GetAreaCost(area);
}
return cost;
}
private bool AtPosition(Vector3 destPos, Vector3 currentPos)
{
return Mathf.Abs(currentPos.x - destPos.x) <= 0.1 && Mathf.Abs(currentPos.z - destPos.z) <= 0.1;
}
Comment
Your answer
Follow this Question
Related Questions
How to tell if a looked at object has a text mesh. 0 Answers
Raycast inconsistent 1 Answer
Making a GameObject follow the direction of a RayCast 1 Answer
2D Raycast Script 0 Answers