The*_*ate 4 javascript vector angle direction
我有这个简单的函数来设置矢量的角度.它有效地获取向量的当前幅度(长度),计算角度并将角度从弧度转换为度.然后我将角度应用于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;
}
Run Code Online (Sandbox Code Playgroud)
但是我不确定如何从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
}
Run Code Online (Sandbox Code Playgroud)
此尝试不会返回除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;
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6483 次 |
| 最近记录: |