Skip to content

Instantly share code, notes, and snippets.

@viig99
Created July 2, 2012 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viig99/3033111 to your computer and use it in GitHub Desktop.
Save viig99/3033111 to your computer and use it in GitHub Desktop.
Scrolling Direction.
/* This Function determines the direction of your displacement based upon the width and height of the widget / viewport width height you are scrolling them.
The theta is calculated based upon the width and height of the widget, and sets the direction based upon the 4 quadrants which are formed due to the intersection of lines drawn from the vertices and the point on origin on the center of the widget.
This Leads to a cleaner user experience for scrolling, as this works smoothly for small or large widgets.
@Arjun Variar
*/
function returnDirectionOfScroll(deltaX,deltaY,width,height) {
var angle = Math.atan2(-deltaY,-deltaX).toDeg();
var theta = Math.atan(height/width);
angle = angle > 360 ? (360 - angle) : angle;
if ( angle <= theta || angle > (360 - theta))
return "left"
else if (angle <= (360 - theta) || angle > (180 + theta))
return "down"
else if ( angle <= (180 + theta) || angle > (90 + theta))
return "right"
else
return "up"
}
Number.prototype.toDeg = function() {
return (this * 180/Math.PI) >> 0;
}
Copy link

ghost commented Jul 3, 2012

What will be the return value of each statement given below ?

returnDirectionOfScroll(0, -1, 10, 10);
returnDirectionOfScroll(0, 1, 10, 10);
returnDirectionOfScroll(-1, 0, 10, 10);
returnDirectionOfScroll(1, 0, 10, 10);

@viig99
Copy link
Author

viig99 commented Jul 3, 2012

It would be down, left , left , left. Here the displacements are the difference between each touchmove cords or last touchmove and touchend, which would give the desired direction of movement.

the atan2 values are such ::

Math.atan2( ±0, -0 ) returns ±PI.
Math.atan2( ±0, +0 ) returns ±0.
Math.atan2( ±0, -x ) returns ±PI for x > 0.
Math.atan2( ±0, x ) returns ±0 for x > 0.
Math.atan2( -y, ±0 ) returns -PI/2 for y > 0.
Math.atan2( y, ±0 ) returns PI/2 for y > 0.
Math.atan2( ±y, -Infinity ) returns ±PI for finite y > 0.
Math.atan2( ±y, +Infinity ) returns ±0 for finite y > 0.
Math.atan2( ±Infinity, x ) returns ±PI/2 for finite x.
Math.atan2( ±Infinity, -Infinity ) returns ±3*PI/4.
Math.atan2( ±Infinity, +Infinity ) returns ±PI/4.

from https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/atan2#Example:_Using_Math.atan2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment