So I’m following this tutorial on line of sight and I get the general idea however things have been a bit hit and miss with me getting it working, I’m doing a simple version of the code in this tutorial with no animator or anything and I am just doing a patrolling capsule with line of sight detection. The capsule when detecting the player should turn red, I managed to get it working a little bit but unfortunately it’s just too tricky for me right now without good debugging to see whether or not the raycasting is even working.
I tried putting up some debug logging to at least let me know when the player is even being detected or not and I wanted to draw the raycast using debug as you normally would, however it threw up an error, does anyone know what the proper way of having line of sight show up in your scene as a debug line or something so you can see if it’s being drawn correctly?
Here’s the code I have, it may well be that I have something wrong here and there as well that means the code isn’t connecting the collider to everything properly so that’s why the detection isn’t working so well but I can’t know that if I can’t even see the raycast.
using UnityEngine;
using System.Collections;
public class Patrol : MonoBehaviour {
public Transform [] points;
private int destPoint = 0;
private NavMeshAgent agent;
public float FieldOfViewAngle = 110f;
public bool PlayerInSight;
public SphereCollider col;
private GameObject player;
void Awake ()
{
col = GetComponent<SphereCollider> ();
player = GameObject.FindGameObjectWithTag ("Player");
}
// Use this for initialization
void Start () {
agent = GetComponent <NavMeshAgent> ();
GoToNextPoint ();
}
void GoToNextPoint ()
{
if (points.Length == 0)
return;
agent.destination = points [destPoint].position;
destPoint = (destPoint + 1) % points.Length;
}
// Update is called once per frame
void Update () {
if (agent.remainingDistance < 0.1f)
{
GoToNextPoint ();
}
}
void OnTriggerStay ( Collider other )
{
if (other.gameObject == player)
{
PlayerInSight = false;
Vector3 direction = other.transform.position - transform.position;
float angle = Vector3.Angle (direction, transform.forward);
if (angle < FieldOfViewAngle * 0.5f)
{
RaycastHit hit;
if (Physics.Raycast (transform.position + transform.up, direction.normalized, out hit, col.radius))
Debug.Log ("Raycast Drawn");
{
if ( hit.collider.gameObject == player )
{
PlayerInSight = true;
gameObject.GetComponent<Renderer>().material.color = Color.red;
Debug.Log ("Player Detected");
}
}
}
}
}
}
I noticed that as well despite me being able to change the colour of the capsule at times the boolean itself wouldn’t change and the debug log wouldn’t give me “Player detected” to indicate everything is working, so I wonder what that’s all about. What’s interesting is that the patrolling code works fine and the agent goes to the designated points without any bother, so it must be something to do with the code inside OnTriggerStay.