Search Unity

Physics.Raycast intermittent failure

Discussion in 'Scripting' started by strawberrydoll, Mar 14, 2018.

  1. strawberrydoll

    strawberrydoll

    Joined:
    Jan 15, 2014
    Posts:
    43
    I use a function to generate a randomly moving entity path in my game, I use raycasts to calculate a random path inside of a unit circle. The generation of points for the path looks like this:

    Code (CSharp):
    1. void GenPath()
    2.     {
    3.         int spawning = Random.Range(MINPOSITIONS, MAXPOSITIONS);
    4.         PathPoints = new List<Vector3>();
    5.  
    6.         for (int i = 0; i < spawning; ++i)
    7.         {
    8.             Vector3 pos = (Random.insideUnitCircle * MaxMoveAreaUnityUnits) + new Vector2(transform.position.x, transform.position.z);
    9.             pos = new Vector3(pos.x, transform.position.y, pos.y); // yes both y because ret was vec2
    10.  
    11.             //is there direct path
    12.             RaycastHit hit;
    13.             Vector3 rayDir = pos - transform.position;
    14.             if (Physics.Raycast(transform.position, rayDir, out hit, rayDir.magnitude, 1) == false) //ignore raycast blocked
    15.             {
    16.                 Debug.DrawLine(transform.position, pos);
    17.                 if (Physics.Raycast(pos, Vector3.down, out hit, 1))
    18.                 {
    19.                     PathPoints.Add(hit.point);
    20.                 }
    21.             }
    22.         }
    23.     }
    The image below shows how a ray failed to notice the box collider of the bricks, as a debug line was drawn with a false result from the Physics.Raycast function.



    Stepping through the code shows that it sometimes works and correctly finds the box collider, but some rays fail like the one above. I've been working on this for a few days and I can't get my head around it. Any ideas?
     
    Last edited: Mar 14, 2018
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Hmm, that's very puzzling. I would tackle this by gathering more information: change your code to cast a ray a fixed distance in the transform.forward position, so you can easily and repeatably direct the ray; and always draw a debug line, either to the end of the ray in one color, or to the point hit in another color. And when it hits, maybe also Debug.Log the collider that was actually hit.

    Then use this to probe. Does it work in some region of the bricks and fail in others? Could it be that it's never hitting the bricks, but sometimes hitting some other object you weren't thinking of? Does it depend on the angle or distance?

    There must be some pattern to it — I've never seen Raycast just randomly fail. Keep digging, and I bet you'll find the cause!