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.