- Home /
Raycasting in 2D is not working
So I am trying to check if a user has clicked an object in my 2d game. I am using a 2D knob sprite like the image below, and I have included a circle Collider 2D around the sprite.
This is my code,
//If the left mouse button has been clicked
if(Input.GetMouseButton(0))
{
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), -Vector2.up);
if(hit.collider != null && hit.transform.tag == "Dot")
Debug.Log("Dot Hit");
}
I'm not hitting the Debug.Log inside the inner if statement. Each of my sprite has the tag, Dot. I'm following it just as it says in the documentation. I've checked the mouse is getting clicked, and it does come inside the outer if statement.
EDIT: I tried Debug.Log ing the Camera.main.ScreenToWorldPoint(Input.mousePosition), and even though I am moving my mouse around and clicking randomly, the value that gets printed is always the same.
I don't think a hit circle collider can accept input from a raycast I think you will have to have a sphere gameobject...
hit.collider.gameobject
I may be wrong,
Also,
hit.transform.tag == "Dot"
Is a little slower than hit.collider.gameobject.name = "Dot" because of the tag system.
$$anonymous$$ake sure your raycast are set to hit trigger colliders: Edit > Project Settings > Physics2D > Check "Raycasts Hit Triggers"
Can you send over following data .
1) Game object position .
2) Touch co-ordinates when you're trying to press on that game object .
$$anonymous$$ake sure mapping is properly done because you're casting ray from your touch co-ordinates , if they are somewhere else and your game object is somewhere else , it will not work .
cheers
Your answer
Follow this Question
Related Questions
Raycast for a 2D objects 0 Answers
2d Raycast problem from enemy to player C# 1 Answer
Layer Mask on raycast2d not working? 1 Answer