[C#] how to select what is only on the x/y position the mouse is on?

I have a number of sprites on top of each other with each sprite a small diastase from the other forming something like a hand of cards.

I use the following: RaycastHit2D[] hits = Physics2D.RaycastAll(hit.transform.position,-hit.transform.up,0.6f); to select all objects from the point of click to the bottom.

When i do so the selection is not exactly at the x y position were i click but rather in the center of the object that is selected. The effect of that is:

  • the objects below the selected one is selected
  • also, the objects that is below the full size of the selected object is also selected meaning that not only the objects below the point of click is selected but also the objects below point of click but that is covered by the selected objects size.

Also, when i click on an object in the stack i move that object to the top by default. This is used during the game and what i am trying to achieve is when selecting a group of objects.

Anyone that have an idea how to solve this?

The Solution

…using LinecastAll :slight_smile:

// Select only the objects below the mouse x  y vector
				LayerMask theLayer;
				theLayer = (1 << LayerMask.NameToLayer("Cards")); // set the layer to be clickable
				Vector2 clickedPos = Camera.main.ScreenToWorldPoint (Input.mousePosition); //Get current worldspace position of mouse cursor
				RaycastHit2D[] hits = Physics2D.LinecastAll(clickedPos,clickedPos,theLayer); //Cast ray at the world space the mouse is at