title: Why does my raycast sometimes does detect a hit and sometimes wont?
body: <p>I have a bullet that is fired with a Impuls on the rigidbody.
  Then, each frame i do a raycast forward with the speed of the bullet, which sometimes does, and sometimes doesn't find an enemy.
  When i skip through the game frame by frame, i can clearly see my debug-raycast inside the (boc)collider of the enemy, but it still won't find it. 
  Im pretty sure it doesn't just pass the enemy, in the editor i can clearly see the green raycast inside the collider.</p>
  
  <p>Any suggestions? I also tried with a linecast, which i found on here, but that gives the same result. (the line is on the exact same position and also draws the debug-line inside the collider. The layers are also correct, as i said, sometimes it will, and sometimes it wont find the target...</p>
  
  <pre><code>void Update()
  {
    //get direction and distance
    Vector3 direction = _rigidBody.velocity.normalized;
    float distance = (_rigidBody.velocity.magnitude * Time.deltaTime);
  
    //raycast for targets
    RaycastHit raycast;
    if (Physics.Raycast(transform.position, direction, out raycast, distance, HitLayerMask))
    {
      Debug.DrawRay(transform.position, direction, Color.red);
    } 
    else
    {
      Debug.DrawRay(transform.position, direction, Color.green);
    }
  }
  </code></pre>
  
  <p>You can see the tiny debug ray, aswell als the collider from side-view. It also it almost right in the middle from the front-view.
  I'm thinking it might be because the start and end of the raycast are inside the boxcollider?</p>
  
  <p><a href="https://i.stack.imgur.com/h77eR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h77eR.jpg" alt="Editor Screenshot"></a></p>
  
  <p>the rigidbody is moved by </p>
  
  <pre><code>//Speed = 500 in this case, but lowering doesn't change anything
  rigidBody.AddRelativeForce(Vector3.forward * Speed, ForceMode.Impulse);
  </code></pre>
  
  <p>UPDATE:</p>
  
  <p>After some more debugging and testing, i found that it happens because you won't get a hit from inside a collider.
  Here's what happend:</p>
  
  <ul>
  <li><p>bullet is outside target collider, but raycast is to short to find it.</p></li>
  <li><p>bullet moves forward, enemy also moves forward (closing in on eachother). Bullet is now inside the collider</p></li>
  <li><p>raycast won't find enemy because thats just how raycast work</p></li>
  </ul>
  
  <p>What i could do, is make the distance of the raycast further, but also not so far away that it would result in weird hits that would graphically look weird.</p>
  
  <p>i thought that using </p>
  
  <pre><code>float distance = (_rigidBody.velocity.magnitude * Time.deltaTime);
  </code></pre>
  
  <p>would be enough (since thats the distance the bullet traveled since last frame, but because the enemy also moves, the above can happen. Well, it would be enough if the enemy wouldn't move :/</p>