Issue with Raycast2D

Trying to detect if the mouse has passed over two colliders is not working unless the mouse is moved slowly. If the mouse is moved at speed, only the first collision is detected.

Any ideas?

if (Input.GetMouseButton(0))

{

RaycastHit2D hit = Physics2D.Raycast(mainCamera.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);

if (hit)
{
    if (hit.collider.tag == "validTag")
    {
        if (firstCollider = null)
        {
            Debug.Log("Hit First Collider");
            firstCollider = hit.collider;
        }
        else
        {
            if (hit.collider != firstCollider)
            {
                Debug.Log("Hit Second");i
            }
        }
    }
}

}

Where did you place that code? In FixedUpdate? If so, try putting it in Update.

And a possible workaround would be to store the previous mouse position, then on mousebutton down raycast between the last position and the new position.

1 Like

No, that was in Update.

Raycasting between the current and previous positions to detect a collision is a good idea, I’ll give that a try.

Brilliant mate, that sorted it. Thanks for the help.