Search code examples
unity-game-enginecollision-detectionraycastingunity3d-2dtools

Raytracing not responding correctly


So I'm new to Unity and I'm sure I'm missing an easy step, but after looking online for a while for some reason I can't find the solution.

I have two objects on the screen, player and enemy. Both have Rigidbody2D, and Box Collider 2D attached. On Box Collider 2D I have clicked is triggered On Rigidbody2D for both I have clicked Is Kinematic. On player I have a simple movement script. On the enemy object I have this:

void Update () {
    RaycastHit2D hit = Physics2D.Raycast(transform.localPosition,transform.right,Mathf.Infinity);
    Debug.DrawRay(transform.localPosition,transform.right);
    if (hit)
      Debug.Log(hit.collider);
}

Now for some reason when I move player over the object if (hit) is true, but if I move the player anywhere on the right side it is not true. What would be the reason for this? Thanks.


Solution

  • First of all you don't need Rigidbody for raycast detection, only colliders. Second, Physics2D.Raycast uses world position, not local, so replace "transform.localPosition" with "transform.position", this messes it up a lot if the transform is child of something. Take in mind that you are sending raycast from the right side of your transform, so maybe it's not hitting anything and values you are getting are actually correct.