【问题标题】:Cartesian to polar coordinates笛卡尔坐标到极坐标
【发布时间】:2012-01-17 17:06:43
【问题描述】:

看看这里的例子: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);
    }

鼠标在粒子(中心圆)上方和右侧的位置,例如:

控制台日志显示:

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

应该是 arctan(27/26) = angle : 46 : theta = 0.8。因为即使鼠标位于中心“上方”,它也会将 y2-y1 读取为 -27,因为坐标系统基于左上角的大约 0,0。

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

【问题讨论】:

  • 因为y和x都为负数时,除以正数(即对应角的对数,角正切为正数时,角本身为正数。class="comcopy">跨度>
  • 您可以将许多值传递给将给出相同值的三角函数(sin、cos、tan)。 sin 的明显值是 0、Pi、2*pi、3*pi 等。它们只给出一定范围内的唯一值(例如,对于 sin,它的 -Pi/2 到 +pi/2)。这意味着在执行逆三角函数以返回原始值时,除非您也大致知道它在什么范围内,否则知道三角函数的结果是没有用的。您确定的方法是使用 x 和 y 的符号首先计算出它是哪个象限,从而确定您是否需要加、减或其他任何方法来获得正确的角度。

标签: javascript math geometry cartesian polar-coordinates


【解决方案1】:

在 Javascript 和许多语言中,有一个 atan2 函数来解决这个问题。它是一个接受 2 个参数(xy 坐标)的函数,因此系统可以在结果中添加或减去 π 以产生正确的角度。而不是调用

Math.atan(y/x)

您只需调用

Math.atan2(y, x)

【讨论】:

  • 嗯,好的。当我在 arctan 上搜索 javascript 时,它告诉我功能是相同的,我选择了 atan,因为它没有让读者想知道 atan2 是什么……但这解决了这个问题。
【解决方案2】:

不知道你想怎么画线,但是这两种方法都可以解决你的问题。

 theta = Math.atan2(distance.y , distance.x);
 theta = Math.PI + Math.atan2(distance.y , distance.x);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多