Jetchy Jetchy - 1 month ago 12
Javascript Question

GSAP - Draggable rotate is not accurate or consistent

I'm using the Greenscok Draggable as a themostat. The temperature increases or decrease at every 18 degrees rotation (also based on clockwise or counter-clockwise).

I'm grabbing the rotation and using the remainder operator (%) and if it is equal to 0, the temperature changes.

With the dial at 0 (rotation), the temperature is at 18 and at -180 (rotation), the dial should reach 26 degrees. However, this is constantly changing depending on how fast the dial is moving.

Just to add, the temperature should be at 22 degrees at -90 (rotation).

Here is a jsbin of how far I've got - http://jsbin.com/wanoraputa/edit?html,js,output

Thanks.

Answer

Here is the answer that was provided to me on the Greensock forum.

console.clear();
var output = document.getElementById('output');
var temp = document.getElementById('temperature');
var previousRotation = 0;


//from Blake
function normalize(value, min, max) {
  return (value - min) / (max - min);
}


//from Chrysto
function percentToRange(percent, min, max) {
   return((max - min) * percent + min);
}


Draggable.create('#dial', {
    type:'rotation',
    throwProps: true,
    bounds: {
        minRotation: 0,
        maxRotation: -180
    },
    onDrag: function(){
       var normalized = normalize(this.rotation, 0, -180);
       var mapped = percentToRange(normalized, 18, 26);
       console.log(this.rotation, normalized, mapped, this.getDirection());
       temp.innerHTML = parseInt(mapped);
    }
});

http://codepen.io/GreenSock/pen/ALNzJz?editors=0011