Search Unity

Troubles with Physics2D.Raycast

Discussion in '2D' started by luigi7, Sep 22, 2017.

  1. luigi7

    luigi7

    Joined:
    Jun 30, 2015
    Posts:
    99
    Hello, here is my problem:

    I have 2 GameObjects, one in the "Enemies" layer and one in the "Friendlies" layer, I need the one in Enemies to see the one in Friendlies.

    Here is my code, used from the GameObject in the Enemies layer:

    Code (CSharp):
    1.  
    2.         /// The offset to apply to the cast origin point (by default the position of the object)
    3.         public Vector2 raycastOriginOffset = new Vector2(0,0);
    4.         /// The layers the enemy will try to look at
    5.         public LayerMask targetLayerMask;
    6.  
    Code (CSharp):
    1.  
    2.        RaycastHit2D hit;
    3.        Vector2 raycastOrigin = (Vector2) transform.position;
    4.        Vector2 raycastDirection;
    5.  
    6.       raycastOrigin.y += raycastOriginOffset.y;
    7.       raycastOrigin.x += _targetCharacter.IsFacingRight ? raycastOriginOffset.x : -raycastOriginOffset.x;
    8.  
    9.       raycastDirection = _targetCharacter.IsFacingRight ? Vector2.right : Vector2.left;
    10.  
    11.      Debug.DrawRay (raycastOrigin, raycastDirection * spotDistance, Color.green, 1, false);
    12.    
    13.       hit = Physics2D.Raycast (raycastOrigin, raycastDirection, Mathf.Infinity, targetLayerMask);
    14.  
    15.       if (hit.collider != null)
    16.                 Debug.Log ("Hit: " + hit.transform.gameObject.name);
    17.  
    targetLayerMask value comes from the inspector and is set to Friendlies, so the enemy looks for the friend.
    In the Layers matrix, Enemies and Friendlies collide each other.
    Both GameObjects are IsTrigger, but in Physics2D the Queries hit triggers is checked.
    If I set the targetLayerMask to Everything, the raycast does not hit anyway on Friendlies... but hits other things around, and this confuses me.
    I use to lift a little the raycastOrigin.y, but it seems to be correct as i can se from Debug.DrawRay.

    I am stuck, can't guess where I am doing wrong.
     
  2. luigi7

    luigi7

    Joined:
    Jun 30, 2015
    Posts:
    99
    After hours of mindscrew I made it: probably I had some option around making RayCast to not function as expected, so I deleted some files in Project folder and let Unity to regenerate them.
    Now it works fine.