Generate normalized value from atan2

jersmi's picture

MAth problem. In this js (qtz attached), I have mouse moevment constrained to a circle. Anyone know the correct math for turning atan2(x,y) to normalized output [0, 1]? Essentially I just need to rotate 180 degrees. Can't get it....

function (__number px, __number py, __number norm) main (__number x0, __number y0, __number mouseX, __number mouseY, __number radius)
{
   var result = new Object();
   //x0 = 0;
   //y0 = 0;
   var angle = Math.atan2(mouseX, mouseY);
   var distance = Math.sqrt(Math.pow(mouseX - x0, 2)+Math.pow(mouseY - y0, 2));
   if (Math.ceil(distance) >= radius) {
      result.px = x0 + (Math.sin(angle) * radius);
      result.py = y0 + (Math.cos(angle) * radius);
    } else {
      result.px = mouseX;
      result.py = mouseY;
    }
    //How to normalize for [0,1] range?
    result.norm = angle/3.14159265 + 1;
    //result.norm = angle/Math.PI;
   return result;
}
PreviewAttachmentSize
constrain mouse to circle.qtz22.73 KB

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

jersmi's picture
Re: Generate normalized value from atan2

ah, typos, and can't edit original, sigh....

(also, any js streamlining tips appreciated).

gtoledo3's picture
Re: Generate normalized value from atan2

If you divide any angle by 360 you'll wind up with a 0~1 range result for the first 360 degrees of rotation.

jersmi's picture
Re: Generate normalized value from atan2

Ok, got it.

function (__number px, __number py, __number norm) main (__number x0, __number y0, __number mouseX, __number mouseY, __number radius)
{
   var result = new Object();
   var angle = Math.atan2(mouseX-x0, mouseY-y0);
   var distance = Math.sqrt(Math.pow(mouseX-x0, 2)+Math.pow(mouseY-y0, 2));
   if (Math.ceil(distance) >= radius) {
        result.px = x0 + (Math.sin(angle) * radius);
        result.py = y0 + (Math.cos(angle) * radius);
        } else {
        result.px = mouseX;
        result.py = mouseY;
        }
 
    //Normalize to [0, 1]
    var c = Math.atan2(-(mouseX-x0), -(mouseY-y0));
    result.norm = (c/Math.PI + 1)/2;
 
    return result;
}
PreviewAttachmentSize
circle_dial_normalized.qtz32.81 KB