RaycastHit2D hits itself

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:

publicboolleftCellHit;
publicboolrightCellHit;

voidAwake()
 {
leftCellHit = false;
rightCellHit = false;
Debug.DrawRay (transform.position, Vector2.right, Color.white, 0f, true);
Debug.DrawRay (transform.position, -Vector2.right, Color.red, 0f, true);
 }

voidUpdate() 
 {
RaycastHit2DrightHit = Physics2D.Raycast (transform.localPosition, Vector2.right, 1f);
RaycastHit2DleftHit = Physics2D.Raycast (transform.localPosition, -Vector2.right, 1f);


if (rightHit.transform.tag == "Cell")
 {
rightCellHit = true;
Debug.Log ("RightHit on "+rightHit);
 }else{
rightCellHit = false;
 }

if (leftHit.transform.tag == "Cell")
 {
leftCellHit = true;
Debug.Log ("LeftHit on "+leftHit);
 }else{
leftCellHit = false;
 }
 }

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

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.

1 Like

Thanks MelvMay!