I have an ai car script. The car needs to be able to slow down and or stop if it gets too close to another car. Right now I'm using 3 raycasts like so:
if (Physics.Raycast(lRay, out lHit, rs.forwardCollisionRayLength, rs.rayLayerMask) || Physics.Raycast(rRay, out rHit, rs.forwardCollisionRayLength, rs.rayLayerMask) || (Physics.Raycast(mRay, out mHit, rs.forwardCollisionRayLength, rs.rayLayerMask)))
{
//some code...
}
However this is really long and inconvenient because it's a pain to figure out which raycast actually had the hit. And then there's other cases where multiple raycasts hit the same car, which point do I use, or if different raycasts hit different cars...Anyway, you can see that this is not ideal.
Also, depending on the size of an object, it could go between the raycasts. In the image below, the blue box is ok because its wider than the width between the raycasts, thus two of the raycasts find it. But on the other side, the green pole is too small, so the car can't see it and drives on.
I also need to get the distance between the hit.point and the car so that I know how much the car needs to slow down so that there's a reasonable distance between the two cars at all times.
I could use something like Physics.OverlapBox
or Physics.CheckBox
but then I can't get the distance between the closest point of the car, only the center of it. This is bad because some cars are longer than others - I need the distance between the nearest point of the car.
Also, keep performance in mind, I could solve the problem of objects going in between raycasts by adding more, but that will drain performance hugely, mainly because I have up to about 40 cars running at a time.
TL;DR: What are some alternatives for a raycast that can also give me the distance to the closest point?
if
condition into three differentif
s. That way you will know which ray hit the target. ---- Edit: Do not make performance assumptions, that's Profiler's job. \$\endgroup\$