Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript formula for computing the vector normal

The following question was asked and answered:

Given 2 points how do I draw a line at a right angle to the line formed by the two points?

However, I am wanting to use it in a javascript function and would like to know how to complete the step where the vector is normalised :

The unit vector of the normal vector is given by dividing each component by the length of the vector.

I have no experience of vector mathematics, but in order to obtain the 'rno' vector, I have to take the inverse of the vector and multiply it by the left or the right normal - I think. Can anyone help me understand how to achieve this pls? I think I have to multiply all the components, but am at the end of a long day, and math tutorials are all looking like Greek.

Thanks in advance.

like image 918
miller the gorilla Avatar asked Mar 13 '23 14:03

miller the gorilla


1 Answers

Every vector is defined by to values eg. x and y. Length of the vector is given by equation length = sqrt(x^2+y^2). Operation of obtaining unit vertor is called normalization. As you wrote, in order to normalize vector, we divide each vector component by length.

Here's example of implementation in JavaScript:

First of all, you need to define vector somehow. We'll create new object called Vector. Then we'll add a function which calculate the length and new x, y values.

//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}

Note that is just one of the many possible implementations.

EDIT: You can accually extend your object with length function:

Vector.prototype.length = function() { return Math.sqrt(this.x*this.x+this.y*this.y) }

and check if our v1 vector is properly normalized:

v1.length();
//0.9999999999999999
like image 109
falseinput Avatar answered Mar 24 '23 05:03

falseinput