Raycast with touch not precise

Hey guys, I have a script to detect when a raycast hits a specific object, to display a Debug.Log. Im am using touch inputs with old inputsystem. However when i click slightly away from the object that should be detected, it is detecting it.

I was searching for an answer for like 4 hours, hope someone knows why it isn’t working correctly. if someone didn’t understand the problem please comment.

        if (Input.touchCount > 0 && touch.phase == TouchPhase.Began)
        {
            _startTouchPosition = touch.position;
        }

if (Input.touchCount > 0 && touch.phase == TouchPhase.Ended)
{
_stopTouch = false;
_endTouchPosition = touch.position;
Vector2 Distance = _endTouchPosition - _startTouchPosition;

            if (Mathf.Abs(Distance.x) < tapRange && Mathf.Abs(Distance.y) < tapRange)
            {
                Debug.Log("Tap");
                Vector2 test = Camera.main.ScreenToWorldPoint(touch.position);
                RaycastHit2D hit = Physics2D.Raycast(test, (touch.position));
                if (hit.collider && hit.collider.tag == "Unit")
                {
                    Debug.Log("adsasdasdasd");
                }
            }
        }

Hi!

I suspect that the image is registering a click when it shouldn’t probably because has some extra alpha-ed out pixels.

You can try removing these pixels in a picture editing program and make the image smaller, but I think the better solution is to change the alphaHitTestMinimumThreshold to something above zero. See here how to do that: