笛卡尔坐标到极坐标

Par*_*roX 9 javascript math geometry cartesian polar-coordinates

看一下这里的例子:http://www.brianhare.com/physics/so.html

看看我在使用这两个主要功能的console.log:

    function distanceBetween2pts(x1, y1, x2, y2) {
        console.log("Particle: ("+x1+","+y1+") Mouse: ("+x2+","+y2+")");
        //  Pythagoras Theorem
        // PQ = sqrt( (x2-x1)^2 + (y2-y1)^2 )
        var x = (x2-x1);
        var y = (y2-y1);

        this.radius = Math.sqrt(x*x + y*y);
        this.x = x;
        this.y = y;
    }

    function polar2cartesian(R, theta) {
        this.x = R * Math.cos(theta);
        this.y= R * Math.sin(theta);
    }
Run Code Online (Sandbox Code Playgroud)

当鼠标位于粒子的上方和右侧(中心圆)时,例如: 在此输入图像描述

控制台日志显示:

Particle: (300,250) Mouse: (326,223)
artan(-27 / 26) = angle: -46.08092418666069 - theta -0.8042638494191191
Run Code Online (Sandbox Code Playgroud)

它应该是arctan(27/26)=角度:46:theta = 0.8.因为即使老鼠在中心"上方",它也会将y2-y1读为-27,因为坐标系统基于左上方的0,0.

那么问题是当X和Y都为负时使θ为正,而它应该指向相反的方向(从中心点向外).我知道我可以在这里做一个180度的技巧,但我想知道我做错了什么.

ken*_*ytm 13

在Javascript和许多语言中都有atan2函数来解决这个问题.它是一个带有2个参数(xy坐标)的函数,因此系统可以对结果加上或减去π以产生正确的角度.而不是打电话

Math.atan(y/x)
Run Code Online (Sandbox Code Playgroud)

你只需要打电话

Math.atan2(y, x)
Run Code Online (Sandbox Code Playgroud)