Hi Zac
A few bits here. First up, as pointed out by pako, if what you want is a ray from the transform.position to finalDetected.transform.position, you have the maths the wrong way round. To calculate a vector that goes from A to B, the calculation is OFFSET = B - A.
A side note is that directions are typically normalized (i.e. of unit length), though its possible the raycast function does this for you internally.
First thing I would do here is use the debug utilities to draw your ray in the editor and make sure it is correct. See here: Unity - Scripting API: Debug.DrawRay
A quick blast at the code (without testing) would be something like:
//precompute our ray settings
Vector3 start = transform.position;
Vector3 direction = (finalDetected.transform.position - transform.position).normalized;
float distance = detectionOptions.detectionRange;
//draw the ray in the editor
Debug.DrawRay(start,direction*distance,Colors.Red);
//do the ray test
RaycastHit2D sightTest = Physics2D.Raycast(start, direction, distance);
if (sightTest.collider != null)
{
if (sightTest.collider.gameObject != gameObject)
{
finalDetected = null;
Debug.Log ("Rigidbody collider is: " + sightTest.collider);
}
}
With it drawn on screen you should know for certain if the ray is doing what you think it should be doing.
Following that, you might be seeing an issue as you are only asking the ray for the first object it hits (thats what Physics2D.Raycast does). So if it hits something else you won’t get your enemy. That’s fine if you definitely want the first object hit, but if there’s stuff you want to ignore and you aren’t using layer masks, you’ll need to handle manually.
You can limit this problem by filtering based on layer (see Cam’s answer), but if you still need to check all objects along the ray, use the raycastall function, and iterate over the results:
//precompute our ray settings
Vector3 start = transform.position;
Vector3 direction = (finalDetected.transform.position - transform.position).normalized;
float distance = detectionOptions.detectionRange;
//draw the ray in the editor
Debug.DrawRay(start,direction*distance,Colors.Red);
//do the ray test
RaycastHit2D[] sightTestResults = Physics2D.RaycastAll(start, direction, distance);
//now iterate over all results to work out what has happened
for(int i = 0; i < sightTestResults.Length; i++)
{
RaycastHit2D sightTest = sightTestResults*;*
- //do stuff with this result? not sure exactly what your function needs though :)*
}
The results come out sorted (closest first), so you could identify:
- stuff you wanted to ‘block’ the line of sight - break out of loop with ‘false’
- stuff you don’t care about - just continue looping
- stuff you want to detect hitting - break out of loop with ‘true’
You could even use more debug draw functions to show where the ray cast hit to help you work out what is happening.
Hope that helps!
-Chris