- Home /
Problems with finding the clicked sprite
First, I know there are functions that automatically get called when a sprite is clicked, but I have to calculate everything from another script which sprite gets clicked.
Anyway, here's the code:
Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );
RaycastHit hit;
if( Physics.Raycast( ray, out hit, 100 ) )
{
......................
Basically, it never makes it past that if. What am I doing wrong?
Answer by robertbu · Apr 13, 2014 at 01:35 AM
Sprites are 2D. Physics.Raycast() is 3D. You have to use some sort of 2D function to detect the hit on a 2D object. Note Sprites by default do not have a collider, so you will also need to add some sort of collider to your sprite. Then you can do something like:
var hit : RaycastHit2D = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if (hit != null && hit.collider != null) {
Debug.Log("object clicked: "+hit.collider.tag);
}
An alternate approach (assuming an orthographic camera) would be to use Camera.ScreenToWorldPoint() and then test the position using Physics2D.OverlapPoint() or Physics2D.OverlapPointNonAlloc().
But shouldn't the 3D version technically work too? Unity does have Z coords even for 2D. And a sprite after all, is just a quad.
@noatom - All raycasting requires a collider. Physics.Raycast() only raycasts against against 3D colliders. Physics2D.Raycast() raycasts only against the 2D colliders. You cannot have a 2D and a 3D collider on the same game object. You could place a box collider or a mesh collider on a child object and then your code would work. Raycasting is all about the colliders and has nothing to do with the mesh. You can put a 2D collider on a complex 3D mesh, or a 3D collider on a sprite. Assu$$anonymous$$g you did not need to handle 2D collisions for your sprite, you could use your code and add a box collider (or any 3D collider) to the game object.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Help me With clamping gameobjects Codes inside. 1 Answer
Raytrace Ignore the x axis ? Or Am I just a noob ? x') 0 Answers