Flashlight Intensity with ScrollWheel

I’m trying to make my flashlight change its intensity by using the scrollwheel up and down. I figured it’d be a drain light script. I’m not so good at scripting though, so I gave it a shot anyways and this is what I came up with.

function Update ()

if(turnedOn) {
     float f = Input.GetAxis("Mouse ScrollWheel");
     lightSource.intensity += f * intensityFactor;
     drainSpeed += f * drainFactor;
}

If anybody could help me i’d be forever greatful

Thanks

I believe that Input.GetAxis(“Mouse ScrollWheel”); returns the delta (or change in) the axis from the last update.

Therefore you need to calculate where you are in your range using that change.
Mathf.Clamp: will let you set a minimum and maximum range

    var maxIntensity: float = 10; //max
    var minIntensity: float = 1; //min
    var changeSpeed: int = 5;

    
    function Update(){
        lightSource.intensity = Mathf.Clamp(lightSource.intensity - Input.GetAxis("Mouse ScrollWheel")*changeSpeed, minIntensity, maxIntensity);
    }

So say our intensity is currently 5, and we click the scroll wheel down once (lets say this = 0.2).

Then script says:

New intensity = 5 - 0.2 * 5

New intensity = 5 - 1

New intensity = 4

(Also mathf.Clamp will make sure that this is within the min an max range.)

The change in intensity should be working. Be mindful that most mouse wheel inputs give small numbers such as 0.1. You may need to increase your intensity factor to notice a difference. I would have the intensity factor at around 10.0 .

Secondly you haven’t shown any other code surrounding your drainSpeed variable. The drainSpeed variable will increase in proportion with an increase in your light intensity. You should have some code else where that will minus the drainSpeed variable from a ‘battery’ variable. I would put this battery variable at 100.0 . Once the battery reaches 0.0 you should change turnedOn to false.

You will also obviously need a chargeSpeed variable, that only acts upon the battery when turnedOn is false. I’ll just put the code below. :stuck_out_tongue:

var lightSource : GameObject;
var totalCharge : float = 100.0;
var chargeSpeed : float = 5.0;
var intensityFactor : float = 10.0;
var drainFactor : float = 1.0;

private var turnedOn : boolean = false;
private var currentCharge : float;
private var drainSpeed : float;

function Start (){
   currentCharge = totalCharge;
}

function Update (){
 
   if(turnedOn && currentCharge > 0.0) {
      var wheelInput : float = Input.GetAxis("Mouse ScrollWheel");
      lightSource.intensity += wheelInput * intensityFactor;
      drainSpeed += wheelInput * drainFactor;
      currentCharge -= drainSpeed;

   }else if(currentCharge <= totalCharge){
      turnedOn = false;
      lightSource.intensity = 0.0;
      currentCharge += chargeSpeed;
   }

  if(Input.GetKeyDown("f")){
    if(turnedOn){
       turnedOn = false;
    }else{
       turnedOn = true;
    }
  }

}