I have a object on the screen, and i need to know if the point i clicked in the screen, is on the left/right/above or below my object.
To do so, i’m doing the following :
posicao.x = Input.mousePosition.x; posicao.y = Input.mousePosition.y;
var ray = Camera.main.ScreenPointToRay (Vector2(posicao.x,posicao.y));
hits = Physics.RaycastAll (ray, 400.0);
Having the hitpoint, i then compare it with the right/up transform of my object :
newPoint1 = naveInimiga + naveInimiga.transform.right;
newPoint2 = naveInimiga + naveInimiga.transform.up;
if(newPoint1.x > hit.point.x)
{
// I'm on the left
}
etc
This code works fine, however, i have a problem.
When i rotate the Camera, this code stops working, as it continues to assume to old Camera rotation.
What do i need to change here, so this code works independent of the camera rotation ?
Well, this is for a formation movement.
I have a diferent formation shape, in case the units go to the left/right/up or down.
So,i need to know what formation do i build, depending if the user clicks on the left/right, etc.
If the camera rotates, that code i have below, won’t work.
I don’t know what naveInimiga means so I could be wrong here, but assuming it’s the object you want to compare to, your algorithm won’t work. You are comparing the hit points to the object in world space, which means it will only work when the camera is looking approximately along the world’s z-axis.
This problem is much easier to solve using Camera.WorldToScreenPoint (Unity - Scripting API: Camera.WorldToScreenPoint). Just use that function with the position of your object and you can directly compare the result to your mouse position in screen space.