Fixed my Raycast problem, but I'd like to know WHY this fix works. [Raycast distance parameter]

Hey folks,

since I don’t feel comfortable using rigidbodies, I’ve decided to write my own collision script using raycasts. The function below is called from the player script, which sends the corresponding data as well. ‘distance’ is the playerSpeed * Time.deltaTime

void CheckCollision(Vector3 rayPosition, Vector3 rayDirection, float distance)
{
        RaycastHit rayHit;

        if (Physics.Raycast(rayPosition, rayDirection, out rayHit, Mathf.Infinity))
        {
            float distanceWeCanMove =  Vector3.Distance(position, rayHit.point) - minimumDistance;

            if (distanceWeCanMove <= 0)
                return 0f;

            if (distanceWeCanMove >= distance)
                return distance;

            return distanceWeCanMove;
        }

        return distance;
}

At first the raycast distance was 1f. I choose this since distance is usually a small number, and it seemed efficient to not make the raycast too long. After doing lots of monkey-testing, it turned out the object could sometimes still glitch through walls. After changing the raycast distance to Mathf.Infinity however, this hasn’t happened anymore. How come the raycast distance makes such a big difference, while the the distance parameter is such a small value?

First of all, there’s a version of the function, that doesn’t use distance, you should use that. I think, your problem was, that your speed was over 1unity/tick, or something like that, and the raycast just bypassed the object. My second thought was, that your character thickness is over 2 units, and that somehow screwed up the raycasting.

  1. I thought that as well, but that can’t be it. At some point I even replaced the 1f by (distance * 2) and it would bug out even sooner…
  2. Nope, it’s just a simple 1 unit block. It doesn’t get send from the middle either, but from the side.

Can you show some images, of the setup you’re using

The cube in the middle has the playerscript on it. The raycasts get send from the outer bounds + 0.01f.