I’m working on a small mobile game. In it I used a raycast to be able to tell when player clicks on a certain object. Suddenly I noticed a weird behavior when one object was covering another. It sometimes returned the the object behind instead of the one in the front. After some testing I learned that RaycastHit was returning a wrong hit position. This is where I got stuck I started debugging for hours(I even went to the second page on google reading all the threads with similar issues) I was about to give up, but then I commented a bit of code that modified the position of objects. It suddenly started working.
This is the code that made raycast stop working it was called in every FixedUpdate:
Vector2 position = gameobject.transform.position;
position.x = 0.5f*targetx+ 0.5f*position.x;
gameobject.transform.position = position;
I started trying different things to fix it and changing the above code to this one below made it work again:
gameobject.transform.position = new Vector3(targetx * 0.5f + 0.5f * gameobject.transform.position.x, gameobject.transform.position.y, gameobject.transform.position.z);
Can someone explain me WHY changing the code above to the one below fixed it? I’m pretty sure that they both do exactly the same thing.