【问题标题】:Rotation of a point around origin in 2D converge to 02D中围绕原点的旋转收敛到0
【发布时间】:2018-12-01 03:58:17
【问题描述】:

编写以下代码以在 2D 中围绕原点旋转一个点。然而,它并没有绕圈子,而是不断地向中心汇聚。 (最初在 Three.js 上运行)此代码绝对正确。 (我在其他平台上也做过,甚至在 excel 表中也做过数值模拟)。

为什么会这样?

<body>
    <div id="vals"></div>
    <script>

        theta = Math.PI / 90.0;
        var x = 1;
        var y = 1;

        var element = document.getElementById("vals");

        var i;
        for (i = 0; i < 10000; i++){
            var r = Math.sqrt( x * x + y * y );
            var para = document.createElement("pre");
            var node = document.createTextNode("x="+x+"     y="+y+"     r="+r);
            para.appendChild(node);
            element.appendChild(para);
            x = (x * Math.cos(theta)) - (y * Math.sin(theta));
            y = (y * Math.cos(theta)) + (x * Math.sin(theta));
        }
    </script>
</body>

附言 我知道,如果我将值归一化并乘以幅度,我会得到正确的答案。但是我想知道为什么这个确切的东西不起作用。

【问题讨论】:

    标签: javascript math rotation trigonometry


    【解决方案1】:

    首先,您应用 更改 x 值来获取 y。这是错误的。而是记住旧值并使用它。

         var tempx = x;
         x = (x * Math.cos(theta)) - (y * Math.sin(theta));
         y = (y * Math.cos(theta)) + (tempx * Math.sin(theta));
    

    第二:重复使用相同的值会导致错误累积,因此半径可能会收敛 - 正如您所见。所以更准确的方法是存储初始值并使用当前角度(不是角度差)旋转它们

        var x0 = 1;
        var y0 = 1;
    
            in the loop:
        x = (x0 * Math.cos(theta * i)) - (y0 * Math.sin(theta * i));
        y = (y0 * Math.cos(theta * i)) + (x0 * Math.sin(theta * i));
    

    【讨论】:

    • 哦,我真是个白痴。非常感谢你为我挑选出来。 :)
    猜你喜欢
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 2018-08-03
    • 1970-01-01
    相关资源
    最近更新 更多