Scripting a Dimmer

Hi everyone,

Thanks in advance for your insight. I’m trying to figure out how to script a dimmer - as I rotate an object along its Y axis I want it to dim a light as it approaches some arbitrary amount of degrees (180 or 360 for instance). I use C#. Any thoughts? Thanks again!

So you need three steps: 1) Figure out the angle, 2) turn that angle into a percentage, 3) apply that to the light. Let’s work backwards.

#3 is easy: make a public Light variable, and then set its .intensity to the value.

#2 involves a bit of math, but is also pretty straightforward. The magic word is normalize - you want to normalize the value between your extremes, or put it between 0 and 1. You have values A and B representing min and max, and you need to figure out what percentage along those point C is. The formula for this is simple:

float normalizedValue = (rot - minimum) / (maximum - minimum);

The first step is the hardest - turning a Quaternion (e.g. transform.rotation) into a single numerical value. Whatever you do, DON’T fall into the trap of using transform.eulerAngles for this (or anything). In this case, you’ll want to use the Atan2 function described in that article. You’ll want to use transform.rotation * Vector3.up (assuming that “up” represents the direction your knob’s little arrow thing points), and then use those Y and X values in the Atan2 call.

(Keep in mind that Atan2 gives you back radians, so convert that to degrees before trying to compare it to degree amounts!)

Note that at some point along the “circle”, it has to cross from 0 to 360. If you find that that cutoff is in the middle of the range through which you need to be turning, you can easily tweak the resulting value to “move” the cutoff to some other angle.

angle = (angle + 90f) % 360f;
1 Like

Thank you again! You’ve been so helpful on this forum. I will try and parse this and give it a go tonight! Thanks for taking the time! :slight_smile: