Take the 2-minute tour ×

I cannot make this ray to follow my mouse cursor.

It's always inverse on X axis.

I think that the problem is with my atan function, but since my trigonometry is fairly low, I have no idea how to fix this one.

This is how I calculate radians:

 var dx = target.x - center.x;
 var dy = target.y - center.y;

 var rad = Math.atan2(dx, dy);
share|improve this question
-Math.atan2(dx, dy) is the solution –  6502 Dec 18 '12 at 23:30
Has the same result as my solution (fiddle - take care for your console to don't blow up), but indeed, a minus sign is easier to type than changing the position of the 2 operands. Changing the position of the operands should provide a 1 byte compression gain when minifying though. =] –  Fabrício Matté Dec 18 '12 at 23:38
Math.atan2(dy,dx) is the correct usage. –  Shmiddty Dec 18 '12 at 23:50
add comment

1 Answer

up vote 1 down vote accepted
var dx = center.x - target.x;


The fiddle above doesn't work in Firefox as FF doesn't natively support event.offsetX/Y for mouse events, I assume your normalization code was cut off when making the minimalistic example but I'll leave my normalization code here for future reference:

function normOffset(event) {
    if (typeof event.offsetX === 'undefined' || typeof event.offsetY === 'undefined') {
        var targetOffset = $(event.target).offset();
        event.offsetX = event.pageX - targetOffset.left;
        event.offsetY = event.pageY - targetOffset.top;

Then just pass the jQuery event object to it.


share|improve this answer
Well, my actual example is much more different, I just was stuck with that atan and wrote a quick fiddle. This fixed it, though, thanks. –  jolt Dec 18 '12 at 23:22
Yes I thought that'd be case. =] Just added my normalization code so my fiddle works in a cross-browser way. –  Fabrício Matté Dec 18 '12 at 23:23
add comment

Your Answer


