0
\$\begingroup\$

I appreciate any help you can offer me. I created a script for a character controller that casts two rays below the player's gameobject. The rays extend infinitely and should collide with another gameobject called terrain. The player is directly above the terrain, so the Raycast must return information about that collider (terrain has a BoxCollider2D). The code I'm using is below. Thank you so much for your time and your help.

Why won't my Raycast hit the BoxCollider2D that is directly in front of it?

 public int distanceFromCenter; // set to 1 in inspector
 private float rayDistance = Mathf.Infinity;


 void Update () {
     Vector3 transformUp = transform.up;
     Vector3 transformRight = transform.right;
     RaycastHit leftRayHitInfo;
     RaycastHit rightRayHitInfo;

     Vector3 leftRayOrigin = transform.position + distanceFromCenter * transformRight;
     Vector3 rightRayOrigin = transform.position - distanceFromCenter * transformRight;
     Ray leftRay = new Ray(leftRayOrigin,-transformUp);
     Ray rightRay = new Ray(rightRayOrigin,-transformUp);
     Debug.DrawRay (leftRayOrigin,-transformUp*5000,Color.white); // for visualization 
     Debug.DrawRay (rightRayOrigin,-transformUp*5000,Color.white); // for visualization

     bool castLeftRay = Physics.Raycast (leftRay, out leftRayHitInfo, rayDistance);
     bool castRightRay = Physics.Raycast (rightRay, out rightRayHitInfo, rayDistance);
     if (castLeftRay) {
         Debug.Log ("leftray true");
     } else {
         Debug.Log ("leftray false"); // the console always prints this
     }
 }
\$\endgroup\$
1
  • 1
    \$\begingroup\$ What is your question? \$\endgroup\$
    – bummzack
    Mar 15, 2015 at 9:34

1 Answer 1

1
\$\begingroup\$

I figured it out! Physics cannot be used with 2D colliders like BoxCollider2D. I switched to Physics2D and everything works fine.

Thanks!

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .