- Home /
The question is answered, right answer was accepted
AI Awareness
Hi everybody,
I have code written that makes the enemy follow me based on my proximity to them. What I would like to do to enhance this, is make it so that the enemy would not respond to my presence if I am standing behind him. This would allow for more specialized animations and head shots etc.
I'm just curious what code allows for the AI to have no awareness of things behind the front of their face/back of the head.
Thank you
Answer by whydoidoit · Mar 21, 2013 at 10:59 PM
It's easy enough to test the angle between the player and the enemies facing using the "Dot Product" which is the cosine of an angle and is helpfully a number between +1 and -1.
So:
var dot = Vector3.Dot((player.transform.position - enemy.transform.position).normalized, enemy.transform.forward);
dot > 0, player is in front of the enemy
dot = 0, at right angles
dot < 0, player is behind the enemy
Obviously you can use other values (0.5 is 45 degrees etc).
Answer by Loius · Mar 21, 2013 at 10:58 PM
distanceToPlayer = player.position - transform.position;
angleToPlayer = Vector3.Angle(distanceToPlayer, transform.forward);
// 0 <= angleToPlayer <= 180
// angleToPlayer == 180 -> player directly behind
// angleToPlayer == 0 -> player directly in front
// angleToPlayer == 90 -> player either directly left or directly right (or directly above or below)
if ( angleToPlayer < myPeripheralVisionAngle ) DetectedPlayer();
@Louis - ah @Dr_GeoFry was waiting for an answer for 2 days and then 2 came along at once :)
Answers on UA are like buses...
@whydoidoit thanks guys. Actually the situation I was looking for help in is how do I make the enemy unaware of me if I approach him from behind. Currently, the enemy becomes aware of me when I come within a certain distance of him. I want him to be completely unaware of me if I approach from behind.
Right so you can use either Louis's answer or $$anonymous$$e. In Louis's you need to have the enemy be unaware when the angle is > 90 (or whatever) and in $$anonymous$$e when the dot value is < 0 (or whatever) - just add that to your distance test.
@whydoidoit I added this code:
var dot = Vector3.Dot((target.transform.position - enemy.transform.position).normalized, enemy.transform.forward);
Ins$$anonymous$$d of player, I substituted target, because the player is the target. This is a part of the enemy AI script. I get this error when I want to test:
An instance of type 'UnityEngine.Component' is required to access non static member 'transform'.
Follow this Question
Related Questions
Crowd AI Simulation Advice/Recommendations 0 Answers
Script to detect a death fall 2 Answers
I want my 2D character to fall down as chain after he dies 1 Answer
Death on impact with water 1 Answer
Character disappears when dies. 3 Answers