Is my target to my left or right ?

When we make the A.I of our npcs they should know if the target they want to follow is to the right or left relatively to them.

To do so we will use the the point in the world where our target is.In unity we can use transform.InverseTransformPoint(Transform.Position)

This function give us in return  the Position of the given Transform, basically if  our gameObject orientation is parallel to th y axis all we would have to do is a verification on the x by comparing MyGameObject.Transform.Position.x and MyTarget.Transform.Position.x . If the transform of the Target is smaller than our position then the target is to our left, otherwise, if it is greater, it’s to our right and if it’s the same the target is in front of us.

 

The problem is that our npc will rotate and it’s left will no more be just be given by a comparison of the worlds axis’s x. So By using the  InverseTransformPoint(Transform.Position) what we do is getting a plane point relative to our orientation. Then if the returned point X is Lower than Zero the target is to our left, if greater it’s to our right.

 

In green the new worlds points

This will work both in 2D and in 3D and by changing the compared axis we can change to the needed orientation.

 

The code we used in unity :

private int RighOrLeft() {
        Vector2 relativePoint = transform.InverseTransformPoint(target.transform.position);
        if (relativePoint.x < 0)
        {
            return 0;
        }
        else if (relativePoint.x > 0) { 
                return 1;
                }
        else{
        return 2;
        }
    }