mil*_*lla 4 javascript math vector
提出并回答了以下问题:
但是,我想在 javascript 函数中使用它,并想知道如何完成向量标准化的步骤:
法向量的单位向量是通过将每个分量除以向量的长度来给出的。
我没有向量数学的经验,但为了获得“rno”向量,我必须取向量的倒数并将其乘以左法线或右法线 - 我认为。任何人都可以帮助我了解如何实现这一目标吗?我想我必须将所有组件相乘,但在漫长的一天结束时,数学教程看起来都像希腊语。
提前致谢。
小智 6
每个向量都由值定义,例如。x 和 y。向量的长度由等式 length = sqrt(x^2+y^2) 给出。获得单位vertor的操作称为归一化。正如您所写,为了对向量进行归一化,我们按长度划分每个向量分量。
下面是 JavaScript 的实现示例:
首先,您需要以某种方式定义向量。我们将创建名为 Vector 的新对象。然后我们将添加一个函数来计算长度和新的 x、y 值。
//creating Vector object
var Vector = function(x,y) {
this.x = x;
this.y = y;
}
Vector.prototype.normalize = function() {
var length = Math.sqrt(this.x*this.x+this.y*this.y); //calculating length
this.x = this.x/length; //assigning new value to x (dividing x by length of the vector)
this.y= this.y/length; //assigning new value to y
}
var v1 = new Vector(2,4) //creating new instance of Vector object
v1 // Vector {x: 2, y: 4}
v1.normalize() // normalizing our newly created instance
v1 //Vector {x: 0.4472135954999579, y: 0.8944271909999159}
Run Code Online (Sandbox Code Playgroud)
请注意,这只是许多可能的实现之一。
编辑:您可以使用长度功能来acacually扩展您的对象:
Vector.prototype.length = function() { return Math.sqrt(this.x*this.x+this.y*this.y) }
Run Code Online (Sandbox Code Playgroud)
并检查我们的 v1 向量是否正确归一化:
v1.length();
//0.9999999999999999
Run Code Online (Sandbox Code Playgroud)