- Home /
enemy's line of sight
I know this is probally simple but how can I add in a max distance of the enemy's line of sight. So that if I'm within a certain angle and a certain distance the enemy can see me. And two, I have two debug.drawray that draws an angle to represent its angle sight view. So how can I connect both end-points of each line so it become a cone?
Vector3 rayDirection = player.transform.position - transform.position;
// Detect if player is within the field of view
if((Vector3.Angle(rayDirection, transform.forward)) < fieldOfViewRange)
{
if (Physics.Raycast (transform.position, rayDirection, out hit))
{
if (hit.transform.tag == "Player")
{
//GetComponent<NavMeshAgent>().destination = player.position;
renderer.material.color = Color.yellow;
//Debug.Log("Can see player");
isAlterted = true;
}
}
I unsure of your logic here, but for the specific question you ask use the form of Raycast() that takes a distance parameter:
static bool Raycast(Ray ray, RaycastHit hitInfo, float distance = $$anonymous$$athf.Infinity, int layer$$anonymous$$ask = DefaultRaycastLayers);
Or check the distance to the object hit:
if (Vector3.Distance(transform.position, hit.transform.position) < someValue)
You could achieve with two easy steps: First cast a sphere to check what's in the desired distance. For this you can use OverlapSphere. This will return every collider which is inside a given radius (aka. max distance on visibility)
http://docs.unity3d.com/Documentation/ScriptReference/Physics.OverlapSphere.html
Just saw you already had the angle part, so use the above code to check what's inside your radius and only check the angles for those objects.
Answer by Sparrowfc · Nov 20, 2013 at 07:59 AM
It's quite unnecessary to use Raycast in your case, since you have the reference of the sepcific target.
if(Vector3.Angle(rayDirection, transform.forward) < fieldOfViewRange && Vector3.Distance(transform.positon, player.position) < alertRange)
will just be fine. Anyway, if you insist on using raycast you can write like this
if (Physics.Raycast (transform.position, rayDirection, out hit, alertRange))
Check 'Handles.DrawSolidArc' in Unity Documents and follow it's example code if you want to debug advanced visual info.
Your answer
Follow this Question
Related Questions
How do I Debug.DrawLine through an array of Vector3? 1 Answer
Debug.DrawLine doesn't work 1 Answer
ScreenPointtoRay Problem, how does it work!?! 1 Answer
2 raycasts on the fpwalker/camera 1 Answer
raycasting issue 1 Answer