微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么点绕原点旋转会失去与原点的距离?

如何解决为什么点绕原点旋转会失去与原点的距离?

我试图在 JavaScript 中计算点的旋转,我发现这些值在 1% 的范围内(并且总是在大约正确的角度,但离旋转点更近 1%)。这比浮点不精确所引入的误差要大得多,而且在同一方向上也太可靠了。

下面是演示代码和问题的 HTML/JavaScript。输出行 36 显示了将点 (100,100) 旋转 10 度 36 次的结果。因此,应该在 (100,100) 的大约 .000000001 以内。但它更接近于 (57,57)。

绘制点时,它正在制作蜗牛壳图案。 IE。一个衰败的轨道。谁能看到我做错了什么?

<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <title>Why is the rotation losing distance to origin?</title>
</head>
<body>
<script>
    let x = 100; let y = 100;
    let Cx = 0;  let Cy = 0;
    let rotation = 10 * Math.PI / 180; // 10 degrees as radians

    for(let i = 0; i <= 36; i++) {
        if (i > 33 || i < 3) { document.write(i + ": {" + x + "," + y + "} <br />"); }
        else if (i === 33){ document.write(".<br />"); }
        else { document.write("."); }

        // Rotate 10 degrees from the last position.
        x = Math.cos(rotation) * (x - Cx) - Math.sin(rotation) * (y - Cy) + Cx;
        y = Math.sin(rotation) * (x - Cx) + Math.cos(rotation) * (y - Cy) + Cy;
    }
</script>
</body>
</html>

在此先感谢您的帮助。

解决方法

问题在于这两个语句:

x = Math.cos(rotation) * (x - Cx) - Math.sin(rotation) * (y - Cy) + Cx;
y = Math.sin(rotation) * (x - Cx) + Math.cos(rotation) * (y - Cy) + Cy;

第一条语句用旋转后的值覆盖 x 的值,然后使用旋转后的值计算旋转后的 y 坐标。试试这个:

let x1 = Math.cos(rotation) * (x - Cx) - Math.sin(rotation) * (y - Cy) + Cx;
y = Math.sin(rotation) * (x - Cx) + Math.cos(rotation) * (y - Cy) + Cy;
x = x1;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。