- Home /
Clicking on GameObject in 2D
My game object has a rigid body 2d, a box collider 2d, and a circle collider 2d. I want to check if the object has been hit from my update. It only ever seems to hit something when i increase the size of my colliders, but at that point it is always colliding with the object. Below is my script. I have tagged the object with the tag "Robot".
void Update ()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if(hit.collider != null && hit.collider.tag == "Robot")
{
clicked = !clicked;
Debug.Log("HIT");
}
else
{
Debug.Log("Did not hit anything");
}
}
anim.SetBool ("Clicked", clicked);
}
Any ideas on what i am doing wrong? It seems to either never hit, or hits when im clicking far away from where the object actually is.
Answer by fafase · Aug 27, 2015 at 06:38 AM
Your best shot is to attach a3D boxcollider or plane collider to your 2D sprite and use that one for your raycast.
Using OnMouseDown has been buggy, using raycast2D will not work as it is not meant to use the z value and finally RaycastHit uses the 3D engine while your sprite colliders are registered in the 2D engine.
Answer by msiqueroli · Aug 27, 2015 at 06:10 AM
Create a script in the robot and place:
void OnMouseDown()
{
if(gameObject.tag == "Robot"){
Debug.Log("HIT");
}
else{
Debug.Log("Did not hit anything");
}
}
Answer by k234234w · Aug 27, 2015 at 12:31 PM
I got it to work with OnMouseDown but will be switching to touch input so I will like to get the raycast working. I will try the approach @fafase suggested of adding a 3d box collider or plane collider. Do most people add a 3d collider to their 2d sprite in order to detect clicks/tocuh? It is now an orthographic camera, but i believe when i posted this question it was not as i was in a test scene and didnt realize it was not in orthographic mode @Denvery. So in moving forward would it be best to add a 3d collider?
Your answer
Follow this Question
Related Questions
Player sinking into walls and floor with Raycasts 1 Answer
2D raycast on mobile is giving weird results 0 Answers
2D click on object with a raycast not working 2 Answers
Shooting style like enter the dungeon 0 Answers
2D Slope acceleration 1 Answer