I was having a lot of issues with some camera code I ported from Unity and just realized why it was broken.
The value I am getting with RayCastHit’s Distance value is not a correct value for me and I can’t figure out if there is some sort of unit conversion I am missing or what.
Below is a real example -
Hit Distance: 0.9384555
Vector3 Distance: 123.10932
I was able to get the correct result by using Vector3.Distance() with the ray origin and hit point.
Here is the code that does not work:
public float GetAdjustedDistance(Vector3 position)
{
float distance = -1f;
for (int i = 0; i < desiredClipPoints.Length; i++)
{
Ray ray = new Ray(position, desiredClipPoints[i] - position);
RayCastHit hit;
if (Physics.RayCast(ray.Position, ray.Direction, out hit, float.MaxValue, collisionLayer, false))
{
if (distance == -1)
{
distance = hit.Distance;
}
else
{
if (hit.Distance < distance)
{
distance = hit.Distance;
}
}
}
}
if (distance == -1f)
{
return 0f;
}
else
{
return distance;
}
}
Here is the code that works:
public float GetAdjustedDistanceFixed(Vector3 position)
{
float distance = -1f;
for (int i = 0; i < desiredClipPoints.Length; i++)
{
Ray ray = new Ray(position, desiredClipPoints[i] - position);
RayCastHit hit;
if (Physics.RayCast(ray.Position, ray.Direction, out hit, float.MaxValue, collisionLayer, false))
{
var customDistance = Vector3.Distance(ray.Position, hit.Point);
if (distance == -1)
{
distance = customDistance;
}
else
{
if (customDistance < distance)
{
distance = customDistance;
}
}
}
}
if (distance == -1f)
{
return 0f;
}
else
{
return distance;
}
}