Raycast2D doesn't seem to work correctly.

Hello,

I’m trying to make a simple top-down game with guns, but the script used to shoot the gun does not seem to be working. The following code block is part of a script that is attached to the player. This method is called every time the player presses the mouse:

void PistolShot()
    {
        Vector2 origin = transform.position;
        Vector2 end = mainCamera.ScreenToWorldPoint(Input.mousePosition);
        Vector2 direction = (end - origin).normalized;
        int Layer = LayerMask.GetMask("Shootable");
        RaycastHit2D hit = Physics2D.Raycast(origin, direction);
        if( hit.collider.IsTouchingLayers(Layer))
        {
            GameObject targetObject = hit.transform.gameObject;
            Enemy target = targetObject.GetComponent<Enemy>();
            if (target != null)
            {
                target.TakeDamage(10);
            }
        }
    }

Also, the enemy script looks like this:

public class Enemy : MonoBehaviour {

    public int health;

    void Start()
    {
        health = 50;
    }

    public void TakeDamage(int damage)
    {
        health -= damage;
        if(health <= 0)
        {
            Destroy(this.gameObject);
        }
    }
}

The problem is that when I click to use the gun, either the raycast doesn’t hit the enemy’s collider, or it doesn’t seem to be calling the TakeDamage method on the enemy. Either way, when I try to shoot at the enemy, it doesn’t make the health any lower. When I use Debug.DrawLine(origin, end), the line drawn seems to go right through the enemy, but I don’t think the ray is being cast correctly.

Any help would be greatly appreciated!

Alright, it doesn’t work correctly? What does it refuse to do?