Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating angle in degrees of mouse movement

I want to calculate the angle of the mouse move in degrees. While I know you don't have to move the mouse in a straight line, I was just trying to calculate it based on starting and end points to create a nice right angle.

log("ANGLE: " + getAngle(x1, y1, x2, y2)); is giving weird results:

ANGLE: 0.24035975832980774 
mouse has stopped
ANGLE: 1.334887709726425 
mouse has stopped
ANGLE: 0.2722859857950508
mouse has stopped
ANGLE: 0.3715485780567732
mouse has stopped

Code:

        $("canvas").mousemove(function(e) {                 
            getDirection(e);
            if (!set) {
                x1 = e.pageX, //set starting mouse x
                y1 = e.pageY, //set starting mouse y
                set = true;
            }   
            clearTimeout(thread);
            thread = setTimeout(callback.bind(this, e), 100);
        });

        function getAngle (x1, y1, x2, y2) {
            var distY = Math.abs(y2-y1); //opposite
            var distX = Math.abs(x2-x1); //adjacent
            var dist = Math.sqrt((distY*distY)+(distX*distX)); //hypotenuse, 
               //don't know if there is a built in JS function to do the square of a number
            var val = distY/dist;
            var aSine = Math.asin(val);
            return aSine; //return angle in degrees
        }

        function callback(e) {
            x2 = e.pageX; //new X
            y2 = e.pageY; //new Y

            log("ANGLE: " + getAngle(x1, y1, x2, y2));
            log("mouse has stopped");   
            set = false;
        }
like image 980
user3871 Avatar asked Apr 10 '14 02:04

user3871


3 Answers

Use the atan2 function to get an angle in the full circle,

radians = Math.atan2(y2-y1,x2-x1);

Additionally, you may want to log the values of x1,x2,y1,y2 at the time of computation, it would be better to just have one place where the mouse position is traced. At the moment, you update the position (x2,y2,t2) every 10ms, but (x1,y1,t1) every time the mouse is moved. This can result in very unpredictable sample combinations.

like image 168
Lutz Lehmann Avatar answered Nov 18 '22 03:11

Lutz Lehmann


Your calculations seem to be right, but the problem is that Math.asin(val) returns values in radians. Use the following function to convert to degrees:

Math.degrees = function(radians) {
    return radians*(180/Math.PI);
}

And then call Math.degrees(Math.asin(val)) and it should work!

like image 35
MShah Avatar answered Nov 18 '22 05:11

MShah


The Math.asin() function returns the angle in radians. If you multiply by 180/pi, you'll get the answer in degrees.

Additionally, since you want more than 90 degrees, you should drop the Math.abs call so that you can have a negative value for aSin.

like image 1
gcochard Avatar answered Nov 18 '22 04:11

gcochard