# Angles and Linecasting

I’m working on a script to control guards in a stealth game. I think I’m misusing the angle command or physics.linecast in some way, because it’s not working. I want to get the angle between the guard and the player relative to which way the guard is facing so that if the player is within 40 or so degrees of the center of the guards vision they are considered seen and if they’re in the next 20 degrees they are considered in the peripheral vision and the guard will turn to the player until the player is seen. My code for this segment is below along with a picture hopefully illustrating what I’m trying to do. If anyone could explain my error in this, that would be excellent. Thanks!

``````                distance = (transform.position - target.position).magnitude;
if(distance < 300f)
{
Vector3 angle = (transform.position - target.position).normalized;
float rangle = Vector3.Angle(transform.forward, angle);
if(rangle < 120 && rangle > 85) //periferal vision
{
//raycast, if uninterupted, check movement, if moving, turn to get player in normal vision
int layerMask = 1 << 2;
RaycastHit hit;
if (Physics.Linecast(transform.position, target.position, layerMask) == false)
{
Debug.Log("In Perifery");
if(target.GetComponent<CharacterController>().GetMovement() != Vector3.zero)
{
Debug.Log("In Perifery moving");
}
}
}
else if (rangle < 85) //normal vision
{
//raycast, if uninterupted, player is seen
int layerMask = 1 << 2;
if (Physics.Linecast(transform.position, target.position, layerMask) == false)
{
contact = true;
Debug.Log("In Vision");
}
}
}
``````

I have some code that does that in a 3d world… maybe you can adapt it? This uses a cone from the eye.

I would run and see if it is in the greater arc then the minor arc so you don’t do double work when you don’t need to.

``````float CheckSightArc(Vector3 npc, Vector3 pc)
{
float Angle = Vector3.Angle (pc - npc, transform.forward);
return Angle;
}

bool SeePlayer()
{
Vector3 npcPos = new Vector3 ();
npcPos = transform.position;
Vector3 playerPos = FP.GetComponent<Transform> ().position;
npcPos.y += raiseTransformBy;
Ray visRay = new Ray(npcPos, playerPos - npcPos);
RaycastHit playerHit;
Debug.DrawRay (npcPos, playerPos - npcPos, Color.green);
if (Mathf.Abs(CheckSightArc(npcPos, playerPos)) < Sight_Arc && Physics.Raycast (visRay, out playerHit, Sight_Range))
{
if(playerHit.collider.tag == "Player")
{
EngagePlayer();
return true;
}else
{
if(debug_toggle)Debug.Log ("My view is blocked by something with the tag of: " + playerHit.collider.tag);
}
}
return false;
}
``````

why not use LookRotation. then simply subtract the new rotation from your characters current rotation to see if you are less than 20?

`````` var looking = Quaternion.LookRotation (enemy.position - transform.position);
``````