# Unity Raycast2d Hitting GameObject That Isn't There?

I’m making a 2d checkers game and I’m using raycasts on every tile to see if there is a piece that is forced to move (jump over another piece). I also tried using linecasts but it always gives me the same results. It seems like my raycasts are very inconsistent with which piece to hit. Here is what is does:

As you can see, the rays are sometimes hitting and sometimes not hitting tiles. Here is the code:

``````List<GameObject> ScanForPossibleMoves()
{
forcedPieces = new List<GameObject>();

for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
Ray ray = new Ray(cam.transform.position, new Vector3(x, y) - cam.transform.position);
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity, 1 << LayerMask.NameToLayer("Piece"));

if (hit)
{
Debug.DrawLine(cam.transform.position, new Vector3(x, y));
print(hit.transform.name);
}
}
}
return forcedPieces;
}
``````

I also checked all the layers in my game:

I don’t know why this is going on. I tested with this many times but it has never worked. Does someone know the answer to why this isn’t working?

Why are you trying to do 3D raycasts in a 2D physics system? Using that “Ray” thing is also odd, not sure why you’re creating it then extract what you put in.

A 2D physics system only exists in a 2D plane, in Unity this the XY plane.

So just use Physics2D.OverlapPoint(new Vector2(x, y)) or if you need to check to see what’s between two points then use Physics2D.Linecast and pass both points.

Thanks so much I didn’t know OverlapPoint existed! It’s hitting the piece perfectly now!

1 Like

Glad you got it working. Always worth grabbing a drink and just browsing/testing the Physics2D namespace; lots of useful stuff available there.