Touch screen tap and raycast2D to hit moving object
Hello, I am working on my own project and learning unity. I came up with following code using various sources, to destroy touched objects. The thing is objects are in free fall motion with rigidbody2D, gravity and detection set to continuous. When I tap on them on the phone, I can't hit them. I have to tap their bottom side to be able to score a hit. Objects have circle2d colliders which doesn't leave any part of the visual outside.
It feels like physics and visuals and tap have sync problems. There isn't any obvious delay between my touch being registered. It feels like when i tap on object, object already moved further(it is on free fall) than visual location and my raycast doesn't hit it.
I searched on the internet the most related thing was moving raycast to fixed update. Which I did but problem didn't change. It runs at locked 30fps on my phone. Phone spec snapdragon 855. Shouldn't be performance problem.
I think, I am doing something very wrong but still couldn't find it.
This is not my exact code but, simplified it without removing performance related stuff. I appreciate any kind of suggestions for solving this problem
Edit: Same problem persisted when I used everything in 3d or moved everything to update, used orthogonal vs perspective camera .
void Update()
{
if (Input.touchCount > 0)
{
hitRegistered = true;
hitPos = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
}
}
void FixedUpdate()
{
if (hitRegistered)
{
hitRegistered = false;
RaycastHit2D hit = Physics2D.Raycast(hitPos, Vector2.zero);
if (hit)
{
Food food = hit.transform.gameObject.GetComponent<Food>(); // My script with
eaten = food.name; // string
Destroy(hit.transform.gameObject);
}
}
Eaten.text = eaten; // UI text
}