Evertjan. wrote:

giloosh wrote on 15 jun 2006 in comp.lang.javascript:

how would i get the distance and angle between 2 points on the screen.

For example:

what is the distance between (100,50) and (250,70)

what i really wanna do is see how far the current mouse position is

from a given object and what the angle is between them.

There can't be an 'angle' between points, there can be between vectors

or you can calculate a direction or bearing from one to the other.

If we stipulate pixels as being square,

[that is the same distance horizontally as vertically]:

<script type='text/javascript'>

r = Math.atan2(50-70,250-100)

Depending ... if the OP wants the direction from the first point to the

second, then:

r = Math.atan2(70-50, 250-100)

is required. More thought may be needed - see below.

alert(r + ' radians')

d = r *180 / Math.PI

alert(d + ' degrees')

</script>

I hope this is right!

Guessing that the OP really wanted the direction from the first point

to the second, and in a mathematic system (zero extends to the right,

90 degrees is straight up) then it's nearly "right".

The general solution using atan2 for the direction from A to B is:

dx = Bx - Ax

dy = By - Ay

r = atan2(dy, dx)

The OPs example is A=(100,50) and B=(250,70) so the solution should be:

r = atan2( 70-50, 250-100)

Which is about 0.13 radians or 7.6 degrees.

Left at that, some results will be negative (e.g. from (0,0) to (1,-1)

gives -45 degrees). Depending on the OPs requirements, that might be

OK but it likely will confuse humans. If a system is needed where

directions are always positive, then add:

if (r < 0) r += Math.PI * 2;

Now -45 degrees will be 315 degrees and directions continuously

increase from zero to 360.

The above is based on a mathematic Cartesian system, what about if a

normal mapping system is required, where zero and north are straight

up, 90 degrees and east are to the right and bearings increase

clockwise? The sense is opposite and the origin is rotated 90 degrees

- but the fix is easy: just swap dx and dy in the atan2 expression:

r = atan2(dx, dy)

And you're done. The example points above give a bearing from A to B

of 82.4 degrees, which is 90-7.6. :-)

--

Rob