- Home /
How would I shoot out a ray where the mouse is clicked and check for collision in 2D.
Basically what I want is to convert the code below into 2D so that it can detect the 2d colliders tags that the ray hits. I had this working in my 3d project, however simply making everything their 2D counterpart does not work. If someone could help me I would be eternally grateful.
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
if(hit.collider.tag == "whatever")
{
Do something;
}
Answer by robertbu · Sep 20, 2014 at 07:03 PM
For an Orthogonal camera:
Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Collider2D c = Physics2D.OverlapPoint(pos);
if (c != null && c.tag == "whatever") {
// Do something
}
Note you can also use OnMouseDown() on the object to be clicked.
Wow I feel so dumb. I kept trying to use screentoworldpoint, but forgot to change my camera over to ortho. Thanks a lot for the help.
You can use ScreenToWorldPoint() with a Perspective camera as long as you set the 'z' parameter to the distance in front of the camera on the screen position before making the call.
Your answer
Follow this Question
Related Questions
How add click area? 1 Answer
RaycastHit returns object without collider, in wrong layer 1 Answer
Casting a ray when using overlayed cameras (orto and perspt) for GUI and game? 1 Answer
3d map of all colliders in scene 1 Answer
Eyetracking and colliders,Mesh or Box colliders for static objects for eye tracking 0 Answers