- Home /
How to determine if enemy is on my left or right hand side?
I have 2 game objects. Game Object A and Game Object B. GO A is facing a direction and I want to know if GO B is on the left or right of GO A.
To illustrate my problem I made a picture:
The red line is the direction I'm facing (the z axis of GO A is pointing that way).
So how can I determine if GO B is facing to the left or right as seen from GO A, regardless of their positions in world space?
Answer by Eric5h5 · Mar 13, 2010 at 02:56 AM
Use InverseTransformPoint:
var otherTransform : Transform;
function Start () { var relativePoint = transform.InverseTransformPoint(otherTransform.position); if (relativePoint.x < 0.0) print ("Object is to the left"); else if (relativePoint.x > 0.0) print ("Object is to the right"); else print ("Object is directly ahead"); }
@Eric5h5 you might would like to start using brackts {} all the time after watching that video.. http://www.youtube.com/watch?v=hQVTIJBZook Strongly recommended if you are dealing with JavaScript!
I do use brackets all the time in my own code (they are put in automatically anyway when writing if statements etc.). When writing forum code I don't.
But when writing forum code it's usually for beginners so I think it's better to include them for best practice. Watch the video anyway.. it's really worth it!
A beginner in Unity doesn't always mean a beginner in program$$anonymous$$g :-)
Old answer but still helped me, was thinking of complicated linear algebraic ways to calculate something that unity has a simple function for.. Thanks! ^.^
Answer by Jason_DB · Mar 13, 2010 at 02:18 AM
You could make two raycasts, one(1) from A directly forward and one(2) from A to B, and then compare the x components of their directions (I think that it would be left if 2.x < 1.x and right if 2.x > 1.x).
I was also thinking about using Raycasts but using InverseTransformPoint seems less complicated and has better performance.
Your answer
![](https://koobas.hobune.stream/wayback/20220612105500im_/https://answers.unity.com/themes/thub/images/avi.jpg)