从方向向量获取角度?
Getting the angle from a direction vector?
我有这个简单的功能可以设置矢量的角度。它有效地获取矢量的当前大小(长度),计算角度并将角度从弧度转换为度数。然后我将角度应用于 X 和 Y,最后将矢量乘以它的原始大小。
this.setAngle = function(degree){
var l = this.length(); //magnitude of vector
var angle = degree*Math.PI/180; //degress converted to radians
this.x=Math.cos(angle);
this.y=Math.sin(angle);
this.multiply(l); //original magnitude
return;
}
但是我不确定如何从 Vector 中获取角度。以下是我的尝试:
this.getAngle = function(){
var angle = Math.atan(this.y/this.x); //radians
var degrees = angle/(180*Math.PI); //degrees
return Math.floor(degrees); //round number, avoid decimal fragments
}
此尝试 return 除了 0 或 -1 之外的任何值。
有什么建议吗?
编辑:
正确方法:
this.getAngle = function(){
var angle = Math.atan2(this.y, this.x);
var degrees = 180 * angle / Math.PI;
return (360 + Math.round(degrees)) % 360;
}
this.getAngle = function(){
var angle = Math.atan2(this.y, this.x); //radians
// you need to devide by PI, and MULTIPLY by 180:
var degrees = 180*angle/Math.PI; //degrees
return (360+Math.round(degrees))%360; //round number, avoid decimal fragments
}
我有这个简单的功能可以设置矢量的角度。它有效地获取矢量的当前大小(长度),计算角度并将角度从弧度转换为度数。然后我将角度应用于 X 和 Y,最后将矢量乘以它的原始大小。
this.setAngle = function(degree){
var l = this.length(); //magnitude of vector
var angle = degree*Math.PI/180; //degress converted to radians
this.x=Math.cos(angle);
this.y=Math.sin(angle);
this.multiply(l); //original magnitude
return;
}
但是我不确定如何从 Vector 中获取角度。以下是我的尝试:
this.getAngle = function(){
var angle = Math.atan(this.y/this.x); //radians
var degrees = angle/(180*Math.PI); //degrees
return Math.floor(degrees); //round number, avoid decimal fragments
}
此尝试 return 除了 0 或 -1 之外的任何值。
有什么建议吗?
编辑:
正确方法:
this.getAngle = function(){
var angle = Math.atan2(this.y, this.x);
var degrees = 180 * angle / Math.PI;
return (360 + Math.round(degrees)) % 360;
}
this.getAngle = function(){
var angle = Math.atan2(this.y, this.x); //radians
// you need to devide by PI, and MULTIPLY by 180:
var degrees = 180*angle/Math.PI; //degrees
return (360+Math.round(degrees))%360; //round number, avoid decimal fragments
}