Multiple raycast in for loop uses same RaycastHit
Hi! I'm quite new to coding and I've been trying to make a "sight" script for my characters, but something's not working and I'm not able to figure out what.
The script works by first taking all objects within viewing distance (using a sphere collider) and then from those getting the ones within a certain angle (Field of View). This works fine, but then when I try to see if the objects that are within the field of view is obscured or not, something's off. It works for one object, but when multiple objects are in view the character sometimes think that only one of them is in plain sight.
The plan was to cast a Linecast between the character and the object and see what it hits. If it hits the same object that its aiming for nothing is obscuring, but if not something is in the way. From what I could gather it seems that the script sometimes uses the same hitinfo for different Linecasts. I don't know if it is something i don't know about the for-loop. I appreciate all help. This is my script:
void OnTriggerEnter(Collider col)
{
if (col.CompareTag("Creature")) { objectsInDistList.Add(col.gameObject); }
}
void OnTriggerExit(Collider col)
{
if (col.CompareTag("Creature")) { objectsInDistList.Remove(col.gameObject); }
}
//This is called in update
void GetCreaturesInView()
{
for (int i = 0; i < objectsInFOVList.Count; ++i) { if (!objectsInDistList.Contains(objectsInFOVList[i])) { objectsInFOVList.Remove(objectsInFOVList[i]); } }
for (int i = 0; i < objectsInViewList.Count; ++i) { if (!objectsInFOVList.Contains(objectsInViewList[i])) { objectsInViewList.Remove(objectsInViewList[i]); } }
//see which objects are in the field of view
foreach (GameObject obj in objectsInDistList)
{
Vector3 objDirection = obj.transform.position - transform.position;
float angle = Vector3.Angle(objDirection, transform.forward);
if (angle < FOV)
{
if (objectsInFOVList.Contains(obj)) { }
else { objectsInFOVList.Add(obj); }
}
else { objectsInFOVList.Remove(obj); }
}
//See if object is obscured or not
//this is where the problem begins I think
for (int i = 0; i < objectsInFOVList.Count; ++i)
{
GameObject obj = objectsInFOVList[i];
if (Physics.Linecast(this.transform.position, obj.transform.position, out RaycastHit hit))
{
if (hit.transform.gameObject == obj)
{
Debug.Log("True Hit: " + hit.transform.name + ", " + "Obj: " + obj.transform.name);
Debug.DrawLine(transform.position, obj.transform.position, Color.green);
if (!objectsInViewList.Contains(obj)) { objectsInViewList.Add(obj); }
}
else
{
//this often runs for the second object in view where the raycasthit is the same as the first.
Debug.Log("False Hit: " + hit.transform.name + ", " + "Obj: " + obj.transform.name);
Debug.DrawLine(transform.position, obj.transform.position, Color.red);
objectsInViewList.Remove(obj);
}
}
}
}
Sorry for the long code but I'm not sure what is important for this problem.