Mouseposition not working correctly?

Hello everyone, im trying to make a simple farming game in 2D. But somethings not working.
When I click on a tile and I check the debug.drawray the ray goes a different direction then im pointing with my mouse. How do i fix this because it almost always says (when im clicking on the left side of my player, on the right side it’s almost always working) that the tile is to far away while im almost standing on it.

I hope someone can help me!

void Click()
{
    Vector2 mousePos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y)); ;
    mousePos = new Vector3(mousePos.x, mousePos.y, 0);

    
    RaycastHit2D hit = Physics2D.Raycast(mousePos, Vector2.zero, 3f);
    Debug.DrawRay(this.gameObject.transform.position, mousePos, Color.red, 3);

        if (hit.collider != null)
        {
            Debug.Log("Clicked on " + hit.collider.name);

            if (hit.collider.CompareTag("Tilemap"))
            {
                Vector3Int cellPosition = tilemap.WorldToCell(mousePos);
                TryChangeTile(cellPosition);
            }
            else if (hit.collider.CompareTag("Enemy"))
            {
                float distanceToPlayer = Vector3.Distance(transform.position, hit.collider.transform.position);
                Debug.Log("Distance to Player: " + distanceToPlayer);

                if (distanceToPlayer <= allowedRadius)
                {
                    hit.collider.gameObject.GetComponent<Enemy>().health -= 2;
                }
            }
        }
        else
        {
            Debug.Log("No object hit.");
        }
    
}

You’re raycasting in the direction of nothing (Vector2.zero).

Do you intend to just use something like Physics2D.OverlapPoint() ?

Also…

Always use named arguments with Physics.Raycast() because it contains many poorly-designed overloads:

Agree on the named arguments but that’s 3D physics. I don’t see poorly designed overloads on the 2D raycast. :slight_smile:

2D fizz is better for sure, but I still see people swapping origin: and direction: … and sometimes those ‘people’ are me. :slight_smile:

And the same issues also apply to distance: and layerMask:

I don’t think there’s any way to improve it: raycasting just needs a lot of args, a lot of those args are the same type (or coercible into the same type) and that to me makes it a “use named arguments” situation.

1 Like

If you want to draw a line from this object’s position to the mouse click position, then you should use Debug.DrawLine, not Debug.DrawRay.

With DrawLine, you specify a start and end point for the line. With DrawRay, you specify a start point and a direction.