【发布时间】:2017-03-03 20:51:29
【问题描述】:
我在下面的代码中有一个奇怪的错误。向下滚动查看图片以供参考此问题。下图中的程序是使用javascript在canvas中绘制的,所以请注意x和y坐标都是正的,所以y坐标相对于图形是倒置的。
let rotateVectors = (vs, t) => {
return sortVectors(Object.keys(vs).map(v => {
console.log(vs[v].vector.direction);
let rateOfRotation = -.01 * (Math.random() * (5-1)+1);
let vector = vs[v].vector
let p = vector.magnitude;
let c = vector.coords;
let x = c.x*Math.cos(rateOfRotation) - c.y*Math.sin(rateOfRotation);
let y = c.x*Math.sin(rateOfRotation) + c.y*Math.cos(rateOfRotation);
return vector(cartesian2dCoordinate(x,y))
}));
}
在循环中调用上述方法以将向量缓慢旋转一些随机量,map函数返回一个新向量,它采用x,y坐标,或者描述向量上升和运行的二维笛卡尔对。
rotateVectors 返回 vs 对象中所有向量的排序列表(按角度排序)。
let vectorDirection = (c) => {
//THE ZERO VECTOR
if(c.x === 0 && c.y === 0) return 0;
//cardinal directions, vertical and horizontal
else if(c.x === 0) return c.y > 0 ? .5 : 1.5;
else if(c.y === 0) return c.x > 0 ? 0:Math.PI;
//q3
else if(c.x< 0 && c.y < 0) return (1+ (Math.atan(-1*((c.y * -1) / c.x))));
//q2
else if(c.x < 0 && c.y > 0) return (Math.PI / 180)*(180 + toDegrees(Math.atan((c.y * -1)/c.x)));
//q4
else if(c.y < 0 && c.x > 0) return (Math.PI / 180)*(toDegrees(Math.atan((c.y * -1)/c.x)));
//q1
else return Math.atan(c.y*-1/c.x);
}
此函数根据其象限返回向量角度的弧度。
在图像一中,任何给定的向量都将从标记为红色的 x 平面旋转,一直旋转到 -y 垂直列。 S->E。
traversal zone 2, reversed direction
在图 2 中,矢量神奇地从 E 平面传送到 S 平面,并朝相反的方向传播。 S->E,然后矢量传送回 image1 中的 -X 平面“S”。
我对用矢量绘制东西比较陌生。我记得在学校里有一点trig,但我已经很长时间没有使用它了。有谁知道这里可能发生了什么?为什么我的向量会瞬移,改变方向,为什么没有向量穿过图像 2 的 S 左侧和图像 1 的 S 下方的空区域?
【问题讨论】:
-
imgur.com/a/Skp5O 空区域图像。没有向量穿过图的这个扇区。
-
你应该在vectorDirection中使用atan2函数,而不是每个象限都有一个case
-
哇......该死的。我向上帝发誓我昨晚一整晚都在尝试 atan2,但什么也没发生。它现在按预期工作。
-
很高兴听到它现在正在工作。那么,问题解决了吗?如果没有其他问题,也可以删除问题。否则你可以自己回答
-
确定。我会回答的。
标签: javascript math vector rotation trigonometry