- Home /
check if front left, front right, back right, back left, Angle of two transforms?
how do you check if enemy is on back left of the character something like that i really want to know how its done something like if(withn 0 and 90)//front right if(within 90 and 180)//back right if(within 180 and 270)//back left if(within 270 and 360)//front left
Answer by robertbu · Feb 24, 2014 at 10:17 PM
You can transform your enemy's position into local coordinates. Things with a negative 'z' will be behind the pivot position. Things with negative 'x' will be on the left. Here is a bit of code to demonstrate. It assumes that when the rotation is (0,0,0), the front of your object is facing positive 'z'. Play with in a new scene to start. Attach it to an object, create a target object in the scene, then drag and drop the target object on the 'target' variable in the script. While running, move the target object around the scene.
#pragma strict
var target : Transform;
function Update() {
var output : String;
var pos = transform.TransformPoint(target.position);
if (pos.z < 0)
output = "Back ";
else
output = "Front ";
if (pos.x < 0)
output += "Left";
else
output += "Right";
Debug.Log(output);
}
here was my version BUT yours works better i'm sure :) thank you!
public Transform p1; // the magnetic pole
public Transform p2;
/*void Update () {
/*float angle = $$anonymous$$athf.Atan2(p2.position.y-p1.position.y, p2.position.x-p1.position.x)*180 / $$anonymous$$athf.PI;//left and right
var relativePoint = p1.InverseTransformPoint(p2.position);//back and front
//print(angle+" "+relativePoint);
if(angle<0){
print ("Object is to the Front");
}
if(angle>0){
print ("Object is to the back");
}
if (relativePoint.x < 0.0){
print ("Object is to the left");
}
if (relativePoint.x > 0.0){
print ("Object is to the right");
}*/
//}
Answer by rcober · Aug 09, 2014 at 04:41 PM
For future reference clarity , as you already stated , you should use InverseTransformPoint to transform to local space:
Vector3 local_pos = transform.InverseTransformPoint(camera.transform.position);
if (local_pos.z < 0)
Debug.Log ("Back ");
else
Debug.Log ("Front ");
if (local_pos.x < 0)
Debug.Log ("Left ");
else
Debug.Log ("Right ");
Your answer
![](https://koobas.hobune.stream/wayback/20220613134618im_/https://answers.unity.com/themes/thub/images/avi.jpg)