Problem in raycast to detect touch in 2D game
I'm trying to figure out code to handle touch on mobile in a 2D game, I'm running into some trouble with Raycasts. I currently have this code for handling touch that is attached to the canvas:
foreach (Touch touch in Input.touches) {
if (touch.phase == TouchPhase.Began) {
Vector2 tapLocation = Camera.main.ScreenToWorldPoint(touch.position);
RaycastHit2D hit = Physics2D.Raycast(tapLocation, touch.position);
if (hit.collider) {
GameObject gameObject = hit.collider.gameObject;
switch (gameObject.tag) {
case "My Tag":
Debug.Log("Touched: " + touch.position.ToString());
Debug.Log("Object location: " + hit.point)
break;
}
}
}
}
However, when I tap on certain sprites, another sprite that is far away is detected as tapped. Here's a sample log:
Touched: (1452.4, 281.6)
Object location: (619.9, 116.9)
If I remove the sprite that is incorrectly being detected, it works:
Touched: (1452.4, 319.1)
Object location: (1380.2, 300.2)
The sprites are all the same (duplicated from a prefab). They all have a Circle Collider 2D attached to them and are about 200px by 200px in size.
I think the problem is here
Physics2D.Raycast(tapLocation, touch.position);
Raycast takes position and direction, Idk if this is the position and direction you want to take... I guess not, specially the direction, maybe you want
Physics2D.Raycast(tapLocation, Camera.main.transform.forward);
or best, maybe the solution for most of the cases, but more inefficient, do it
Ray theRay = Camera.main.ScreenPointToRay (touch.position);
Physics2D.Raycast (theRay.origin,theRay.direction);
Answer by peterzhu2118 · Feb 03, 2019 at 03:04 AM
Solved it! Should be using Physics2D.OverlapPointAll
rather than rays.
Your answer
Follow this Question
Related Questions
How can I make touch input work on my IPhone? 1 Answer
Accessing Raycast collider from another script 0 Answers
Is my Touch Algorithm right? 0 Answers
OnScreen-Stick that moves to the position touched 0 Answers
Adding points for every gameObject on the scene instead of adding points for the destroyed one 0 Answers