- Home /
Raycast not updating inside a trigger collider
I have a camera set up and I'm trying to get it to detect the player once they are in the spotlight, like so:
Once the player enters the trigger, a raycast begins which points from the camera to the player. If there is a clear line of sight then the light turns red, and then back to white once the player exits. However, I'm having some trouble when the player starts behind the wall but then walks into the spotlight. Even though the raycast is in the update code, it seems like it does not work past the initial trigger entry. The light does not turn red if the player starts behind the wall, and then walks out into the raycast. Similarly, if the light is red and the player walks behind the wall while staying inside the trigger the light still remains red.
Also the light will flash red for just a moment when exiting the trigger, not sure why it does that.
So how do I fix this? Is it a matter of the raycast not updating or what? Here is the code that I have on the cone mesh collider:
using UnityEngine;
using System.Collections;
public class CameraSpot : MonoBehaviour {
public Light light;
public GameObject playerObject;
public GameObject cameraHead;
public bool triggered = false;
void Update()
{
if (triggered == true)
{
RaycastHit hit;
Ray ray = new Ray(cameraHead.transform.position, -(cameraHead.transform.position - playerObject.transform.position).normalized);
Debug.DrawRay(ray.origin, ray.direction * 10, Color.yellow);
if (Physics.Raycast(ray, out hit, 1000) && hit.transform.tag == "Player")
{
Debug.DrawRay(ray.origin, ray.direction * 10, Color.white);
light.color = Color.red;
}
}
triggered = false;
}
void OnTriggerStay(Collider player)
{
triggered = true;
}
void OnTriggerExit(Collider player)
{
triggered = false;
light.color = Color.white;
}
}