- Home /
Check if player is in front of enemy?
I have a script that checks whether the player is in line of sight of an enemy using raycasting, however I always want to only return true if the player is in front of the enemy. How would I do that.
Answer by Eric5h5 · Apr 26, 2010 at 04:39 PM
See this answer, except use Z instead of X.
That resource is no longer available. Would you $$anonymous$$d directing me to an updated location?
code from link:
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");
}
Answer by StephanK · Apr 26, 2010 at 04:42 PM
Calculate the angel between your forward vector and the enemy position. If absolute value is bigger than a certain threshold (eg. 90 degrees) it's behind you. To do that there a some very convenient functions:
Vector3 directionToTarget = transform.position - enemy.position;
float angel = Vector3.Angel(transform.forward, directionToTarget);
if (Mathf.Abs(angel) > 90)
Debug.Log("target is behind me");
Not tested but should work.
Well, sometimes even wishes come true... http://unity3d.com/support/documentation/ScriptReference/Vector3.Angle.html
@spree: a month late, but: no, that did not make my wish come true. Read again, more carefully. ;)
Answer by asimov · Jun 25, 2012 at 02:54 PM
I know it's been a month since any comments were left on this, but posting as the link in the answer no longer works. So regarding spree 1's code above, for complete 360 degree detection, I think it should be;
if (Mathf.Abs(angel) > 90 && Mathf.Abs(angel) < 270)
Debug.Log("target is in front of me");
if (Mathf.Abs(angel) < 90 || Mathf.Abs(angel) > 270)
Debug.Log("target is behind me");
Answer by CollosalChris · Aug 06, 2017 at 06:03 AM
Check out InverseTransformPoint as mentioned, but placing code here for better reference:
public Transform cam;
public Vector3 cameraRelative;
void Start()
{
cam = Camera.main.transform;
Vector3 cameraRelative = cam.InverseTransformPoint(transform.position);
if (cameraRelative.z > 0)
print("The object is in front of the camera");
else
print("The object is behind the camera");
}
For people who doesn't work as expected , try to adjust (ins$$anonymous$$d of cameraRelative.z > 0 to do something like this cameraRelative.z > 0.15f ) .