- Home /
Enemy attacks when looked at
I was wondering if it is possible to have it when you look at a gameobject (in a certain range), it will attack you, or in my case just move to the player.
Thanks in advance
To answer your question, yes it's possible. What have you tried already?
Answer by Muuskii · Jul 10, 2012 at 04:33 AM
I just tested this out:
Vector3 Difference = transform.position - Camera.main.transform.position;
float dotproduct = Vector3.Dot(Camera.main.transform.forward.normalized, Difference.normalized);
if(dotproduct > 0) //we are infront of camera, check the angle
{
float angle = Mathf.Acos( dotproduct );
angle *= Mathf.Rad2Deg;
if(angle <= Camera.main.fieldOfView)Debug.Log("I SEE YOU LOOKIN'!!!");
}
It says the camera can see it WAY before it actually can, but it SHOULD be working. You probably need to take the screen width/height into effect somewhere.
If you want more of a minecraft, Enderman effect you can do a raycast straight down the screen's center if the angle's tangent is less than your enemy's renderer extents divided by the distance between them. To cut down on unneeded raycasting.
Thanks! This is just what I needed. I am making a horror game, and if this person starts following you, he will kill you if you turn around at him. It really makes the game tense :D
The "I SEE YOU LOO$$anonymous$$IN" made me laugh, $$anonymous$$uuski :)
Answer by gooongalooo · Jul 10, 2012 at 04:33 AM
can you be more specific? because there are many possibilities ... for example a raycast... or maybe something like this... i just copied some lines of code from a project. what it basically does: it´s checking the directions of target and player. "float myDirection": -1 means enemy is behind, 0 : left/right and 1: enemy is in front of the player...
Vector3 dir = (target.position - transform.position).normalized;
float myDirection = Vector3.Dot(dir, myTransform.forward);
if(dist <= maxAttackRange && myDirection >= 0.2f)
{
/// move or attack or what ever
}
/// if(dist > maxAttackRange) move to player until dist <= maxAttackRange //--> check myDirection //-->attack
just one of many opportunities.
Your answer
![](https://koobas.hobune.stream/wayback/20220613073944im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Controller Collider Script 1 Answer
Manually triggering a script from the editor (utility, macro etc.) 1 Answer
Door Opens When Not In Trigger And Sound Help 1 Answer
How would I go about removing a mesh renderer component on collision with a trigger? 1 Answer
Smooth Camera Follow Script, Weird Movement... Please help! 1 Answer