Stealth Game – Core Code

Below is the core code I used in the stealth game proof of concept. Make sure to follow the instructions carefully.

Place this script on each point light in your scene:

using UnityEngine;
using System.Collections;

public class LightDistancecheck : MonoBehaviour {

  public GameObject player;
  public float range;
  public float dist;
  private PlayerLightDetect playerLightScript;
  RaycastHit hit;
  Vector3 rayDirection;

  // Use this for initialization
  void Start () {
    player = GameObject.FindGameObjectWithTag("Player");
    range = this.light.range;
    playerLightScript = player.GetComponent<PlayerLightDetect>();
  }
  
  // Update is called once per frame
  void Update () {
    dist = Vector3.Distance(player.transform.position, this.transform.position);
    rayDirection = player.transform.position - transform.position;
    Debug.DrawRay(transform.position, rayDirection, Color.cyan);
    if(Physics.Raycast(transform.position, rayDirection, out hit, range) ) {
      if(hit.transform.tag == "Player") {
        float lightIntensity = light.intensity / dist;
        Debug.Log(lightIntensity);
        playerLightScript.lightIntensityOnPlayer = lightIntensity;
        if(lightIntensity > 17) {
          playerLightScript.playerIsInLight = true;
        } else {
          playerLightScript.playerIsInLight = false;
        }
      } 
    }
  }
}

What the Light script is doing is:
-Cast a ray from the light to the player.
-If the range of the ray is within the range of the point light, player is in the light.
-Get the intensity value of the light and divide that by the distance of the ray to the player (regardless of light range) to get density of THIS light on the player.
-Update the player script with the appropriate values.

Place this script on your player:

using UnityEngine;
using System.Collections;

public class PlayerLightDetect : MonoBehaviour {

  public bool playerIsInLight;
  public float lightIntensityOnPlayer;

  void LateUpdate () {
    lightIntensityOnPlayer = lightIntensityOnPlayer - 16;
    lightIntensityOnPlayer = Mathf.RoundToInt(lightIntensityOnPlayer);
    if(lightIntensityOnPlayer < 0) {
      lightIntensityOnPlayer = 0;
    }
    if(lightIntensityOnPlayer > 10) {
      lightIntensityOnPlayer = 10;
    }
  }
}

What the Player script is doing is:
-Subtracting 16 from the intensity variable given by the lights casting on the Player, this is to normalize.
-Rounding the intensity to the nearest integer, more normalization.
-Not allowing the intensity variable to go below 0 or above 10, again to normalize so we have a solid range to work with.

If you have any questions, please feel free to contact me.