- Home /
Some raycasts don't hit the object
Hello,
Some of my raycasts are not hitting the object.
The purple lines are the one i Debug.DrawLine
when I shoot the raycasts (doesn't happen every frame). The white and red lines are the whether the raycasts detected anything and that happens in the DrawGizmos.
In the image below you can see that distances in the inspector
My question is: How is this possible? The Green car has only 1 collider and the code for each raycast is the same.
Utils.FovAction(this.transform.up, this.transform.forward,
this.nrOfRays, this.fov, (direction, index) =>
{
Ray r = new Ray(this.transform.position, direction);
r.DebugDrawRay(Color.magenta, this.detectionRate, this.viewDistance);
this._rayHits = Physics.RaycastAll(r, this.viewDistance, this.layerMask,
this._queryTriggerInteraction);
bool collided = false;
foreach (RaycastHit hit in this._rayHits)
{
if (hit.collider.transform.IsTransformInMyParents(this.bot.transform))
continue;
this.RaycastDistances[index] = hit.distance;
collided = true;
break;
}
if (!collided)
this.RaycastDistances[index] = -1;
});
When I debug I see that the _rayHits is empty.
I've also tried removing the Rigidbody on the green car, but that didn't solve it :(.
Is it always on the edge part of the collider that is not hitting? I heard raycast has some kind of offset. I'm not sure though.
No sometimes it's when it's like 10 range from it too in the center.
Where is the problem? RaycastAll returns all the information for each Ray even if it has not hit anything. Perhaps your problem is the variable name _rayHits which is confusing you.
Using RaycastNonAlloc is considerably faster than the other raycast methods for multiple raycasts.
If you draw the Lines in the order of Raycast, _rayHits.transform != null you can simply draw over the top of the debug line if it hits which I expect would also look a lot less confusing.
I know it does not return anything if it didn't hit anything, but it should hit something?
I'll try that.
I added the magenta lines for this post. Normally it only draws Gizmo lines.
Let's hope NonAlloc solves this somehow ;)
You are using a layer mask. If it doesn't find anything on the right layers it won't hit. You have even drawn the white lines showing the instances where it hasn't hit anything.
I don't think RaycastNonAlloc will solve any of your problems regarding hits or anything. It's just faster. As it looks like you're probably firing 11 rays each time you know exactly what size it needs to be.