I'm using a raycast to detect the player's distance to the ground for a hovercraft game.
The raycast works correctly (returns true and also returns the distance to the first impact) until the moment the craft actually touches the ground. When the player hits the ground, the raycast should theoretically return true and return the distance as near 0f. Instead, it returns false, meaning the raycast isn't colliding with anything over the length of the ray. As a result, it can't find the distance.
I'm having a hard time troubleshooting this, and I wonder if anyone can lend a fresh pair of eyes.
Ray ray = new Ray (transform.position, Vector3.down);
RaycastHit ray_result;
bool hit_ground = Physics.Raycast (ray, out ray_result, optimal_vertical_distance * 2);
if (ray_result.distance < optimal_vertical_distance && vertical_force < max_vertical_force)
{
vertical_force += vertical_acceleration;
}
if ((!hit_ground || ray_result.distance > optimal_vertical_distance) && vertical_force > min_vertical_force)
{
vertical_force -= vertical_acceleration;
}
}
body.AddForce (Vector3.up * vertical_force, ForceMode.Acceleration);
The only time hit_ground worked correctly was when I increased the thickness of the floor from 2 units to 4 units and set the ray to start from 2 units above the craft instead of from the craft itself. I don't understand why it works, though. However, in that example, ray_result.distance seems to be locked at -1.10999, regardless of how far away the craft is.