Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

RaycastHit2D hits itself

Discussion in '2D' started by OceanBlue, Nov 3, 2014.

  1. OceanBlue

    OceanBlue

    Joined:
    May 2, 2013
    Posts:
    251
    Hi

    I have multiple spawns of the same object, each with the tag "Cell"

    I want to detect when another cell is close to a cell.

    So on each cell i have a script:

    Code (csharp):
    1.  
    2. publicboolleftCellHit;
    3. publicboolrightCellHit;
    4.  
    5. voidAwake()
    6.  {
    7. leftCellHit = false;
    8. rightCellHit = false;
    9. Debug.DrawRay (transform.position, Vector2.right, Color.white, 0f, true);
    10. Debug.DrawRay (transform.position, -Vector2.right, Color.red, 0f, true);
    11.  }
    12.  
    13. voidUpdate()
    14.  {
    15. RaycastHit2DrightHit = Physics2D.Raycast (transform.localPosition, Vector2.right, 1f);
    16. RaycastHit2DleftHit = Physics2D.Raycast (transform.localPosition, -Vector2.right, 1f);
    17.  
    18.  
    19. if (rightHit.transform.tag == "Cell")
    20.  {
    21. rightCellHit = true;
    22. Debug.Log ("RightHit on "+rightHit);
    23.  }else{
    24. rightCellHit = false;
    25.  }
    26.  
    27. if (leftHit.transform.tag == "Cell")
    28.  {
    29. leftCellHit = true;
    30. Debug.Log ("LeftHit on "+leftHit);
    31.  }else{
    32. leftCellHit = false;
    33.  }
    34.  }
    35.  
    When I press play I'm constantly getting hits from the cell, even when I've only spawned one (it shouldn't be hitting ANYTHING). What am I doing wrong.

    Essentially, I want SHORT ray casts from each cell and detect when a Cell is getting to close to another Cell.

    Thanks
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,314
    In 4.5.5, by default, a 2D ray/line-cast will detect colliders that overlap the start of the line/ray. As of 4.5.5p2 (patch shipped 23rd Oct), the default behaviour is to not detect such overlaps.

    You can however control this behaviour by going into Project Settings/Physics 2D/'Raycasts Start In Colliders' and turn that option on/off.

    With this defaulting to off for new projects, it's the same as 3D physics.

    Hope this helps.
     
    OceanBlue likes this.
  3. OceanBlue

    OceanBlue

    Joined:
    May 2, 2013
    Posts:
    251
    Thanks MelvMay!