Javascript 矢量旋转
我有以下资料:Javascript 矢量旋转,javascript,vector,Javascript,Vector,我有以下资料: function Vec2(x, y) { this.x = x; this.y = y; } Vec2.prototype.rotate = function(d) { var x = this.x; var y = this.y; this.x = x * Math.cos(d) + y * Math.sin(d); this.y = y * Math.cos(d) - x * Math.sin(d); } var v = new Vec2(0, 1); 及之后: v.
function Vec2(x, y) {
this.x = x;
this.y = y;
}
Vec2.prototype.rotate = function(d) {
var x = this.x;
var y = this.y;
this.x = x * Math.cos(d) + y * Math.sin(d);
this.y = y * Math.cos(d) - x * Math.sin(d);
}
var v = new Vec2(0, 1);
及之后:
v.rotate(90);
向量应该是1,0(或-1,0?),但它返回0.8939966636005579,-0.4480736161291702
为什么会这样?创建一个toRad函数,然后在“d”上使用它
function toRad(Value) {
return Value * Math.PI / 180;
}
Vec2.prototype.rotate = function(d) {
d = toRad(d);
var x = this.x;
var y = this.y;
this.x = x * Math.cos(d) - y * Math.sin(d);
this.y = y * Math.cos(d) + x * Math.sin(d);
}
您的函数也使用了错误的公式,这些公式在我发布的函数中。应该首先将
d
转换为弧度(而不是deg)?我在旋转位使用radInDeg()函数尝试了这一点,但它仍然有错误的值,而且我90%确定此公式使用度。传入的参数是90deg
,您必须将90deg
转换为相应的弧度值(Math.PI/2
),不确定如何使用radInDeg
Math.cos()和Math.sin()都使用弧度。是的,这是我的radInDeg(),但没有帮助。现在返回:1,6.123233995736766e-17@user3786755看来是四舍五入的问题,该值几乎接近于0
。它应该是(-1,0)。请看我的编辑来修正你的方程式。我刚刚添加了一个Math.round(),因为我认为它是舍入的,另外我从一张凌乱的纸上复制了方程式,谢谢。