# Light intensity based on player distance

My code below is a bit messed up due to trying one and another but I can’t get my idea to work properly.

I have a basic point light in my scene and my script attached to it. The target is the player. The var distance calculates the distance between the light and the player. What I want is that the light is off if the player is > 30 away. If the player gets close, the light must shine more brighter and if I walk further away it must dim.

How could I achieve this?

``````var Target : Transform;
var distance : float;
var maxIntensity : float = 3.0;

function Update() {

distance = Mathf.Round(Vector3.Distance(gameObject.transform.position, Target.transform.position));

if(distance>30){
light.intensity = 0.0;
print ("light off");
}

if(distance<30){
light.intensity += Time.deltaTime * distance;
if(light.intensity == 0.0){
light.intensity = 0.1;
}
}

if (Random.value > 0.9 && light.intensity > 0.1) {
StartCoroutine("FlickerLight");
}

}

function FlickerLight() {
while(light.intensity > 0.0) {
light.intensity -= Time.deltaTime * distance;
yield;
}

while(light.intensity < 1.0) {
light.intensity += Time.deltaTime * distance;
yield;
}

light.intensity = 1.0;
}
``````

For your specific question, not dealing with the flickering lights, you can do:

``````if (distance > 30) {
light.intensity = 0.0;
}
else {
light.intensity = (1.0 - distance/30.0) * maxIntensity;
}
``````

Where ‘maxIntensity’ is a variable you define and initialize or you can replace it with a hard-coded value. According to the reference, Light.intensity (and therefore 'maxIntensity) must be set in range of 0 to 8.