- Home /
RaycastHit2D.collider is null - why?
I've already looked at the docs, which say that 'collider' is only null when no collider is hit -- let me show you why I think that's impossible.
Here's the code (C#):
public Transform closestSeenHuman() {
float distanceToClosestSeen = visionRange;
Transform closestSeen = null;
foreach (Transform t in info.targets) {
float dist = Vector2.Distance((Vector2)transform.position, (Vector2)t.position);
if (dist < distanceToClosestSeen) {
float angle = Vector2.Angle (Utils.forward2D(transform, 'd'), t.position - transform.position);
if (angle < fovAngle * 0.5f) {
//Here's the part that matters:
Vector2 direction = (Vector2) t.position - (Vector2) eyes.position;
RaycastHit2D hit = Physics2D.Raycast((Vector2)eyes.position, direction, Mathf.Infinity, ignoreEnemy.value);
//this prints every frame that the human is in view
if (hit.collider == null) print("null collider");
Debug.DrawLine(eyes.position, t.position);
if (hit.collider.transform == t) {
distanceToClosestSeen = dist;
closestSeen = t;
print("seen");
}
}
}
}
return closestSeen;
}
The idea of the function is that if the human is within the scriptholder's vision parameters (both angle and distance) then a raycast is performed which, mathematically speaking, should hit the human or at least something in front of the human!
Here's my scene view: (turns out UA doesn't take images, so I posted a screenshot on Imgur) http://i.imgur.com/CyYAWdY.png
Visually speaking, the raycast has hit the human, and the human has a circle collider centered on its pivot point. What's going on?
Bonus points go to the brave soul who can explain to me why the Zombie's arms get in the way of its sight, even with the layermask.
Answer by brentshermana · Aug 11, 2015 at 09:25 PM
As it turns out I was using layer mask correctly: instead of selecting the layers that I did want to be found, I selected the ones that I didn't want to be detected. this actually solve both of my problems.
Your answer
Follow this Question
Related Questions
Click/Touch on Different part of sprite detected ? 0 Answers
Null Reference Exception issue getting the tag of an object hit by Raycast 2 Answers
Switch GameObjects Tags with javascript 1 Answer
Multiple raycasts from game object 0 Answers
Finding a RaycastHit tag (Null Reference Exception) 2 Answers