- Home /
2D enemy Field of Vision script
Hi, I want to make a script that gives a enemy a field of vision, if the player steps into this field of vision, an alarm is triggered. Its for a 2D platformer, Here's an image to illustrate what I mean. The field of vision will also need to move up and down as it is a camera type enemy.
Any ideas on how I would make a script that does this?
.
Answer by robertbu · Mar 11, 2013 at 05:46 AM
I have no idea what you mean by a "camera type enemy" and why that means it has to move up and down. But if you can define a vector for where the "eyes are," finding out if an object is in the field of vision is simple. For example, say you were using transform.right for your eye position/direction, you could do something like:
if (Vector3.Angle(transform.right, playerPosition - EnemyPosition) < 22.5) {
Debug.Log("I'm seeing the player");
}
Note Vector3.Angle returns an unsigned value. Also this is the angle from the vector and the code measures to each side, so the actual field of vision would be 45 degress.
I meant as in the enemy is a camera (as in the model) and that I would like to move the field of vision up and down so the player can sneak past when it is looking away from the player. Thanks anyway though!
This solution works for the camera. Just use the transform.forward of the camera. Something like:
if (Vector3.Angle(Camera.main.transform.forwardt, transPlayer.position - Camera.main.transform.position) < 22.5) {
Debug.Log("I'm seeing the player");
}
I didn't know you could use an actual camera, I will try both and see which one I prefer, would be neat to actually show what the enemy is looking at on the screen (I was thinking of trying to do something similar anyway), thanks again man!
Ahhh... you were talking about a "figurative" camera. I don't think you want an actual camera. Go back to the first solution (they are both the same solution, just using different vectors). Note if you game is organized as the picture, the vector you need to use for your angle statement is "-transform.right". There is no transform.left, so just negate the right vector.
Your answer
Follow this Question
Related Questions
AI script troubles 1 Answer
How do I animate my enemy randomly with time? 1 Answer
How can an enemy deplete players health? 0 Answers
AI Field of vision 1 Answer
enemy ai going to player 2 Answers