Search code examples
c#unity-game-enginemobile2d

2D raycast on mobile is giving weird results


I'm trying to detect a simple tap on collider in a prototype I'm developing with Unity. The problem is that while it detects the collision it seems to do so way off target at times.

Here is what I have

Vector2 point = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
RaycastHit2D hit = Physics2D.Raycast(point, Vector2.zero);
if (hit.collider != null)
{
          //Do stuff
}

I expect that it would only go off on the colliders alone. I added a little text log to make sure it's not hitting other things.

Here's a little image to explain. Blue is where the tapping should be recognized, red is where I tap with my finger and it still recognizes it like I had hit blue. https://gyazo.com/7462de174d30b2d81a30c17f2bbc62fa


Solution

  • Alright I found the issues. I'll post it here in case anyone else stumble on this kind of issue and can't seem to have it work.

    Simply put, check your camera transform. Mine somehow had an offset of 1 in the Y and it was messing everything up.