Raycast collision not working as expected
Hello,
I am having a problem with my colliders which has been plaguing me for weeks. This game uses node based movement and i have already got a list of nodes in the units range of vision but need to remove any that are blocked by objects and structures.
Here i am checking which nodes have objects blocking them from the units LOS at the unit's eye level. When the unit is further away from objects it seems to ignore them, then when it is closer to them it seems to collide even when not checking a path that passes through the object and still ignores some checks.
I have absolutely no idea what is going wrong here. I have attempted to use SphereCast with a thickness of 0.01f to check if the ray width was a contributing factor but this had the same results.
//Checks if a node has LOS to another
private bool NodeHasLOS(GridNodeScript origin, GridNodeScript target, float observerHeight) {
if (origin == target)
return true;
Vector3 originPoint = new Vector3 (origin.transform.position.x, origin.transform.position.y + observerHeight, origin.transform.position.z);
Vector3 targetPoint = new Vector3 (target.transform.position.x, target.transform.position.y + observerHeight, target.transform.position.z);
RaycastHit hit;
string[] layersToCheck = new string[] {"Terrain", "Structures", "Objects"};
LayerMask mask = LayerMask.GetMask (layersToCheck);
Ray ray = new Ray (originPoint, targetPoint);
float rayLength = Vector3.Distance (originPoint, targetPoint);
if (Physics.Raycast (ray, out hit, rayLength, mask)) {
GameObject line = new GameObject ();
line.name = origin.gameObject.name + "->" + target.gameObject.name + " Hit " + hit.collider.gameObject.name;
line.AddComponent<LineRenderer> ();
LineRenderer lineSegment = line.GetComponent<LineRenderer> ();
lineSegment.material = new Material (Shader.Find ("Particles/Alpha Blended Premultiply"));
lineSegment.SetColors (Color.red, Color.red);
lineSegment.SetWidth (0.01f, 0.01f);
lineSegment.SetPosition (0, originPoint);
lineSegment.SetPosition (1, targetPoint);
GameObject.Destroy (line, 20f);
return false;
} else {
//Unit has open view
GameObject line = new GameObject ();
line.name = origin.gameObject.name + "->" + target.gameObject.name;
line.AddComponent<LineRenderer> ();
LineRenderer lineSegment = line.GetComponent<LineRenderer> ();
lineSegment.material = new Material (Shader.Find ("Particles/Alpha Blended Premultiply"));
lineSegment.SetColors (Color.green, Color.green);
lineSegment.SetWidth (0.01f, 0.01f);
lineSegment.SetPosition (0, originPoint);
lineSegment.SetPosition (1, targetPoint);
GameObject.Destroy (line, 20f);
return true;
}
}