I saw a lot of answers about this question but none makes the job like I wanted.
Examples :
Raycasting to find mouseclick on Object in unity 2d games
Unity 2D Raycast from mouse to screen
How to detect a touch on Box Collider 2d in Unity 4.3
And maybe others…
So, I was searching to for a method to catch 2D colliders raycasting a 3D ray from the camera, knowing it was possible but didn’t remember how.
Searching solutions on the web, I remembered that I had already do something great in a last project. Founded it in my files and re-done it in my new project, I want to share you this method.
The tip is to use the GetRayIntersection method in Physics2D which let us cast an arbitrary 3D ray to catch a 2D collider : look here.
There is its little sister : here.
So you can do something like this :
private void GetTargettedGO ( Vector2 screenPosition )
{
Ray ray = Camera.main.ScreenPointToRay ( screenPosition );
RaycastHit2D hit2D = Physics2D.GetRayIntersection ( ray );
if ( hit2D.collider != null )
Debug.Log ( hit2D.collider.name );
}
And that’s all !
Of course this method doesn’t return anything for now, but from here, it’s easy to do what you want !