x


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.

more ▼

asked Apr 26 '10 at 04:24 PM

Sam Bigos gravatar image

Sam Bigos
136 7 8 12

(comments are locked)
10|3000 characters needed characters left

3 answers: sort voted first

See this answer, except use Z instead of X.

more ▼

answered Apr 26 '10 at 04:39 PM

Eric5h5 gravatar image

Eric5h5
80.3k 42 132 521

That's even easier... ;)

Apr 26 '10 at 04:43 PM StephanK

That resource is no longer available. Would you mind directing me to an updated location?

Aug 01 '12 at 01:58 AM DESTRUKTORR

Updated link.

Aug 01 '12 at 02:19 AM Eric5h5
(comments are locked)
10|3000 characters needed characters left

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.

more ▼

answered Apr 26 '10 at 04:42 PM

StephanK gravatar image

StephanK
6k 39 53 93

I totally wish there was a Vector3.Angel function. :)

Apr 26 '10 at 11:13 PM Eric5h5
Apr 27 '10 at 05:56 AM StephanK

@spree: a month late, but: no, that did not make my wish come true. Read again, more carefully. ;)

May 30 '10 at 04:00 AM Eric5h5

Lol. I see it now... ;)

May 31 '10 at 02:27 PM StephanK
(comments are locked)
10|3000 characters needed characters left

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");   
more ▼

answered Jun 25 '12 at 02:54 PM

asimov gravatar image

asimov
157 19 36 40

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x287
x196
x180

asked: Apr 26 '10 at 04:24 PM

Seen: 3391 times

Last Updated: Aug 01 '12 at 02:43 AM